Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about variable forward referencing

 
krussi rong
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Here is the question:
public class Test{
private int i = giveMeJ();
private int j = 10;
private int giveMeJ(){
return j;
}
public static void main(String args[]){
System.out.println((new Test()).i);
}
}
Why the answer is 0?
not compiler error complaining about forward referncing.
thanks
Krussi
 
Paulo Silveira
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I really dont know!
Inserting a System.out.print() inside the giveMeJ method, shows that the method is being called!!!
 
Francisco A Guimaraes
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think what happens is this: when you call giveMeJ() the variable j is already initialized with its default value, 0 for an int, and assigned to i. After that j is changed to 10 in the line below.Anyone correct me if I�m wrong.
Francisco.
 
Gautam Sewani
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read the JLS rules about forward referencing,that will clear up all your doubts.
Compiler issues forward referencing errors only when it is being used in initializers(static or instance)
Eg:
int i=j;
int j=20;
will give a compile time error,because j variable cant be accesed in initializer statement of i.
Similarly,
int i;
{
i=j;
}
int j=20;
will give a compiler error.
However,if a method is used,then there will be no compiler error and the default value of the variable will be taken.Eg
int i=j();
public int j()
{
return j;
}
int j=10;
Here,the value 0 will be assigned to i.
Because the default value of int is 0.
This topic has been discussed a lot of times in this forum,use the javaranch's search facility.
And I repeat,see JLS for a very clear understanding on this topic.
[note:There is a bug in the java language related to forward referencing in which the java compiler does not act as specified in JLS.Consult sun's website for it]
Thanks
Gautam
 
Paulo Silveira
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Francisco A Guimaraes:
I think what happens is this: when you call giveMeJ() the variable j is already initialized with its default value, 0 for an int, and assigned to i. After that j is changed to 10 in the line below.Anyone correct me if I�m wrong.
Francisco.

that is right!!!
in these loines:
private int i = giveMeJ();
private int j = 10;
simply changing the order:

private int j = 10;
private int i = giveMeJ();
will produce the output expected:10!
thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic