Answer the question
In order to leave comments, you need to log in
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);
}
}
Answer the question
In order to leave comments, you need to log in
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.
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 needYes. you will recompute the value of varSum.
to insert varSum = var1 + var2 + var3; then the result will be
15 and 60.
Maybe there is some method that makes the varSum variableThis will no longer be initialization.
recalculate itself without reinitialization?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question