wood burning stoves 2.0*
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Simple Question!!!!" Watch "Simple Question!!!!" New topic
Author

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
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
The answer is (b). What do you think?
Anonymous
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.
thomas
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.
 
jQuery in Action, 2nd edition
 
subject: Simple Question!!!!
 
Similar Threads
very hard question
initilization of method
getInt()
JQ+ Operator Question!!
resultset problem