9

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?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Jimmy
  • 16,123
  • 39
  • 133
  • 213

2 Answers2

17

The variables are initialized from top to bottom.

This is what happens:

  1. Initially both i and k have the (default) value 0.
  2. The value computed by getInt() (which at the time is 0 + 1) is assigned to i
  3. 20 is assigned to k
  4. 1 20 is printed.

Good reading:

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 1
    +1, when `i` is initialized, `k` still has the default value of `0` – unbeli Nov 21 '11 at 20:31
  • 2
    @HotLicks - There's nothing static about this. – Paul Bellora Nov 21 '11 at 20:39
  • No, it's not handled by the constant pool. Check with `javap` yourself. – aioobe Nov 21 '11 at 20:39
  • @HotLicks, I don't know why you say that. Adding `static` [doesn't really change anything](http://ideone.com/0VHoo). A tip; if you feel rusty, and you're not sure about the answer, either try it out using a compiler of your choice, or don't bother answering / commenting. In the end it will just be considered noise. – aioobe Nov 21 '11 at 21:45
  • I have no idea what you're talking about. Are you saying the compiler does something against the spec if it prints `1 20`? Could you give a reference to the spec in that case? (btw, did you downvote me? if so, why?) – aioobe Nov 21 '11 at 21:58
  • I'm talking about the JVM. There are two ways to initialize a field -- *field initializers* and with executable statements in the or methods. Field initializers can only init to a literal value, while the methods can basically do anything you can do with code. – Hot Licks Nov 21 '11 at 23:13
  • 1
    @HotLicks - I for one am having trouble following you. What's your point? Nothing is being swizzled. And the downvote here is perplexing. – Paul Bellora Nov 22 '11 at 06:20
0

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..