Can anyone answer this simple question please What does the following code print 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); }
} a)It will not compile b)It prints 21,20 c)It compiles but throws an exception at run time. d)It prints 1,20 e)None of the above
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
The answer is (b). What do you think?
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
Hi, After compiling, results are 1, 20. i don't get it. Can someone point out why? Thanks.
thomas
Ranch Hand
Joined: May 26, 2002
Posts: 79
posted
0
Note that the method getInt() is called before k is initialized. So when the method getInt() is called, k has the default value 0. So the method returns 1 and thus i gets initialized to 1.