Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Forward Referencing 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 » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Forward Referencing" Watch "Forward Referencing" New topic
Author

Forward Referencing

M Bhalli
Greenhorn

Joined: Oct 09, 2003
Posts: 9
what will be the output of this program, and why there is no error of forward referencing in this case?
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);
}
}
Thanks!!
Terry McKee
Ranch Hand

Joined: Sep 29, 2000
Posts: 173
The output is 0. I believe the reason for this is because the variable i and variable j are established in memory and set to 0 first. Therefore, at the time the statement
private int j = giveMeJ();
is executed, j is 0 not 10. It is only after this statement that j is assigned 10. If you used the follwing code instead:
public class AQuestion
{
private int i = j;
private int j = 10;
private int giveMeJ()
{
return j;
}
public static void main(String args[])
{
System.out.println((new AQuestion()).i);
}
}

you would get a forward looking reference error.
[ October 10, 2003: Message edited by: Terry McKee ]
M Bhalli
Greenhorn

Joined: Oct 09, 2003
Posts: 9
Thank you terry!!!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Forward Referencing
 
Similar Threads
Angelfire.com....quiz 2
Angelfire.com....quiz 2
from abhilash's quiz
forward refrerences
Access Modifiers