File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes forward refrerences Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "forward refrerences" Watch "forward refrerences" New topic

forward refrerences

Kedar Dravid
Ranch Hand

Joined: May 28, 2004
Posts: 333
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
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

Joined: Dec 08, 2004
Posts: 1
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
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.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
I agree. Here's the link:
subject: forward refrerences
It's not a secret anymore!