Reputation: 16428
I'm studying up for the SCJP exam, upon doing some mock tests I came across this one :
It asks what is the output of the following :
class TestClass
{
int i = getInt();
int k = 20;
public int getInt() { return k+1; }
public static void main(String[] args)
{
TestClass t = new TestClass();
System.out.println(t.i+" "+t.k);
}
}
I thought it would be 21 20
, since t.i would invoke getInt, which then increments k to make 21.
However, the answer is 1 20
. I don't understand why it would be 1, can anyone shed some light on this?
Upvotes: 9
Views: 181
Reputation: 1
jvm will follows like this,
1.identification for non-static members from top to bottom 2.executing non-static variables and blocks from top to bottom 3.executing the constructor......
in the first step jvm will provide default values..on that time variables in readindirectly write only state..
Upvotes: 0
Reputation: 420951
The variables are initialized from top to bottom.
This is what happens:
i
and k
have the (default) value 0
.getInt()
(which at the time is 0 + 1
) is assigned to i
20
is assigned to k
1 20
is printed.Good reading:
Upvotes: 17