permaculture playing cards*
The moose likes Beginning Java and the fly likes another perplexing program Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "another perplexing program" Watch "another perplexing program" New topic
Author

another perplexing program

Jim A Anderson
Greenhorn

Joined: Mar 16, 2004
Posts: 5
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);
}
}


jim
Vicken Karaoghlanian
Ranch Hand

Joined: Jul 21, 2003
Posts: 522
This link will prove to be helpful.


- Do not try and bend the spoon. That's impossible. Instead, only try to realize the truth. <br />- What truth? <br />- That there is no spoon!!!
Jim A Anderson
Greenhorn

Joined: Mar 16, 2004
Posts: 5
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

Joined: Oct 02, 2003
Posts: 11153
    
  16

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: another perplexing program
 
Similar Threads
default constructor
Variable initialization
forward refrerences
Forward Referencing
please explain why the compiler is not complaining and why the output is 0