How is it that the following code prints 0? Why doesn't it throw a compiler error, because of the forward reference to j?
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); } }
Ransika deSilva
Ranch Hand
Joined: Feb 18, 2003
Posts: 524
posted
0
Hi Kedar, I guess it is because the variable j is refered before it is getting initialized so that it returns the defualt value for the int data type, Hope it make sence.
SCJP 1.4, SCMAD 1.0<br />SCWCD, SCBCD (in progress)
Arunkumar Ayyavu
Greenhorn
Joined: Dec 08, 2004
Posts: 1
posted
0
Forward references apply only to the variables. It doesn't apply to the methods.
This restriction is done to avoid circular references. For e.g., int i = j; int j = i; This circular reference issue will not occur in Methods.
But you might ask about this: private void m1() {m2();} private void m2() {m1();} In this example, the compiler doesn't know what the methods do.
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
posted
0
If you search this forum for "giveMeJ" you will see that this question has come up often. Here's Corey's Tipline Article on the topic.