File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Simple Question!!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Simple Question!!!!" Watch "Simple Question!!!!" New topic

Simple Question!!!!

Surya B
Ranch Hand

Joined: May 10, 2000
Posts: 98
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
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
The answer is (b). What do you think?
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi, After compiling, results are 1, 20.
i don't get it. Can someone point out why? Thanks.
Ranch Hand

Joined: May 26, 2002
Posts: 79
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.
I agree. Here's the link:
subject: Simple Question!!!!
It's not a secret anymore!