This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Forward Referencing  RSS feed

 
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!!!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!