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

Forward Referencing

 
M Bhalli
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you terry!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic