Confused over initialisation of instance variables
Asked Answered
D

2

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?

Duckling answered 21/11, 2011 at 20:26 Comment(0)
N
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:

Natalya answered 21/11, 2011 at 20:29 Comment(7)
+1, when i is initialized, k still has the default value of 0Caudal
@HotLicks - There's nothing static about this.Yulma
No, it's not handled by the constant pool. Check with javap yourself.Natalya
@HotLicks, I don't know why you say that. Adding static doesn't really change anything. 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.Natalya
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?)Natalya
I'm talking about the JVM. There are two ways to initialize a field -- field initializers and with executable statements in the <init> or <clinit> methods. Field initializers can only init to a literal value, while the methods can basically do anything you can do with code.Koehler
@HotLicks - I for one am having trouble following you. What's your point? Nothing is being swizzled. And the downvote here is perplexing.Yulma
D
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..

Diakinesis answered 24/11, 2011 at 12:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.