What happens when you run the following program?

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);
   }
}
Explanation
During an object creation fields are initialized in order of their declaration.
The "i" field will be initialized first in the given example. At this time, the "k" field is not yet initialized (it contains a value of 0), and a k + 1 expression will result in 1. After that, a "k" field will obtain a value of 20.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes