Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused over initialisation of instance variables

Tags:

java

scjp

ocpjp

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?

like image 721
Jimmy Avatar asked Nov 21 '11 20:11

Jimmy


1 Answers

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:

  • The Java™ Tutorials: Initializing Fields
like image 163
aioobe Avatar answered Sep 22 '22 09:09

aioobe