• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

another perplexing program

 
Jim A Anderson
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code prints:
0
Why???
public class AQuestion
{
private int i = giveMeJ();
private int j = 10;
private int giveMeJ()
{
return j;
}
public static void main(String args[])
{
System.out.println((new AQuestion()).i);
}
}
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This link will prove to be helpful.
 
Jim A Anderson
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, the program shown in the link is just different enough from the program under consideration that the explanation given in the link doesn't seem to suffice for the present case.
The only explanation I can come up with is that when
private int i = giveMeJ();
is invoked, j has been given a default value of 0 and the j = 10 hasn't occurred yet.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12149
31
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you change it to this

you can see that j is indeed 0 in the giveMeJ() method, but does get set to 10 in the object iteself.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic