Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt on "Vairable declaration & forward reference"

 
Mani vannan
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have come across the following questions in some SCJP mock. (Hope, you dont feel bore for reading the code.)

public class AQuestion
{
private int i = j;
private int j = 10;
public static void main(String args[])
{
System.out.println((new AQuestion()).i);
}
}
I know that the above code is error reported by the compiler, since forward reference problem with the variable j.

Look at this code,

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);
}
}

Here also, forward reference problem, But, how come the it gets compiled without any error & outputs 0? Please clarify this.
 
Jas Oberai
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Manivaanan,
This question has been discussed a lot of times in the past..while i was preparing for the exam..this link provided me the best explanation on forward referencing.I'm sure...after you go through this link you will have no problems understanding these forward refencing scenario's.

http://radio.javaranch.com/corey/2004/05/13/1084483439000.html

Thanks
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34837
369
Eclipse IDE Java VI Editor
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic