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

Forward Referencing to method

 
Yogesh Chhawasaria
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why does this doesnt give forward reference error and how is the value 0 printed out.
I've been preparing so long time but such ques always take me back to Square One !!
 
pallavi utukuri
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
first i is initialized by calling giveMej() at this point j is not initialized therefore default value 0 is taken for j and the same is returned.
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);
}

now if we change like this
private static int j = 10;
first j is initialized to 10 as static variables are first initialized then giveMej() is called as the value of j which is 10 is returned and stored in i. so the output will be 10!
one more interesting thing to note if we change da code like this:
private static int i = giveMeJ();
private static int j = 10;
private static int giveMeJ()
{
return j;
}
now the output is again 0! now am sure u know y it is so....i as it is static is initialized first by calling giveMej() in which j is not yet initialized therefore its defualt value 0 is returned and stored in i.
hope dat helps if am wrong or something missing do let me know thanks
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you add a println statement thus:

you can see the initial (defaulted) values of i and j.
[ April 11, 2004: Message edited by: Barry Gaunt ]
 
Yogesh Chhawasaria
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

if instead of above

Why doesnt this compile. It gives me a forward reference error.
Why doesnt i is asigned 0.
 
pallavi utukuri
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
private int i = j; //1
private int j = 10; //2
this cant compile as j is not initialized or rather not even declared at 1 its initialization and declaration takes place in line 2
instead
private int i = j; //1
private static int j = 10; //2
this will compile as line 2 executes first and the declaration & initialization takes place
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java Language Specification talks about this sort of thing in great detail. By the way, I don't understand all of it, but I know where to find it if I need it.
[ April 11, 2004: Message edited by: Barry Gaunt ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic