This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
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
Joined: May 21, 2002
Posts: 32
posted
0
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
Joined: Mar 20, 2002
Posts: 182
posted
0
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.
Francisco<br />SCJP<br />please use the [code][/code] tags when showing code.Click <a href="http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=ubb_code_page" target="_blank" rel="nofollow">here</a> to see an example.
Gautam Sewani
Ranch Hand
Joined: Apr 19, 2002
Posts: 93
posted
0
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
Joined: May 21, 2002
Posts: 32
posted
0
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