Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple Question!!!!

 
Surya B
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is (b). What do you think?
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, After compiling, results are 1, 20.
i don't get it. Can someone point out why? Thanks.
 
thomas
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic