I am beginner in java and would like to clear an idea about variable initialization. Here is the code --
public class NumberSequence {
private static int n;
public static void main(String[] args) {
print(myTest());
print(myTest());
}
private static int myTest() {
n++;
return n * n;
}
}
with two successive calls of the method myTest() the outputs are 1 and 4. So I understand that the default value of n is 0. So for the first call of myTest(), n would be incremented by one resulting 1 and then the multiply line will be executed, that is, 1 * 1
which is 1
.
For the next call of myTest(), n will be initially 1, then it will be incremented to 2, then the multiplication, that is 2 * 2
which is 4
Now I am trying to do this --
public class NumberSequence {
public static void main(String[] args) {
int m;
m++;
int n = m * m;
print("n = " + n);
}
}
Here it gives complier error that m is not initialized which is obvious. So my question is -- how come compiler doesn't complain in case of the first option where I created myTest() method. There I do not initialize the value of n
. Is it the case that compiler is doing the initialization? I would like to get this clarification.