D
D
DonDroid2017-08-01 21:16:00
Java
DonDroid, 2017-08-01 21:16:00

Do I need to reinitialize Java variables that are made up of other variables?

Good evening.
I noticed the following nuance when working with variables in Java, it
is typical for any types of variables int, String, etc., does not
depend on the modifier - the variable is static or not static:

public class Test {

    static int var1 = 5;
    static int var2 = 5;
    static int var3 = 5;
    static int varSum = var1 + var2 + var3;

    public static void main(String[] args) {
        System.out.println(varSum);
        var1 = 50;
        System.out.println(varSum);
    }
}

The result of the execution will be:
15
15
Although, it would seem that it should be:
15
60
Questions are as follows:
1. Does it turn out that a variable consisting of other variables needs to be
reinitialized every time after changing one of its
components? In this case, after assigning var1 = 50; will need
to insert varSum = var1 + var2 + var3; then the result will be
15 and 60.
2. Maybe there is some method that makes the varSum variable
recalculate itself without reinitialization? For example:
varSum.something() or something(varSum) or something else?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2017-08-01
@GavriKos

A variable does not consist of other variables. It consists of a value and has nothing to do with other variables.
After:
int varSum = var1 + var2 + var3;
varSum will contain the sum of the VALUES of variables var1-var3 and there will be no connection with them.

A
Alexander Korobov, 2017-08-03
@superbadlam

static int varSum = var1 + var2 + var3;
here varSum is declared and initialized, i.e. she's been here for 15 years.
System.out.println(varSum);
here you just print its value to the console.
In this case, after assigning var1 = 50; will need
to insert varSum = var1 + var2 + var3; then the result will be
15 and 60.
Yes. you will recompute the value of varSum.
Maybe there is some method that makes the varSum variable
recalculate itself without reinitialization?
This will no longer be initialization.
But something similar can be implemented using for example javafx Property

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question