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 A question on forward referencing. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A question on forward referencing." Watch "A question on forward referencing." New topic

A question on forward referencing.

neha kanwal

Joined: Jan 30, 2007
Posts: 11
Can anyone please let me understand how the result is comes out to be 0 in the following code.

1. How the output comes out to be 0.
2. If I replaces private int i = giveMeJ(); with private int i = j;, I get compilation error due to forward referencing but why not in the earlier case.

Sanjeev Kulkarni

Joined: Mar 20, 2006
Posts: 26

When you invoke (new AQuestion()).i in your main() method, the result is the value of that 'i' gets initialized with inside the constructor, whose body looks like this:

public AQuestion()
i = giveMeJ();
j = 10;

So, when 'i' tries to get the value from giveMeJ(), 'j' shouldn't have been initialized to 10, rather it would have the 0, the default value for an 'int'. So, i = 0 and the same would be printed.

One Important Point is: The instance variables get initialized in the order
they're read. So, if it were:

private int j = 10;
private int i = giveMeJ();

Then, you would get output as 10.

2) Forward referencing occurs because you're trying to assign a variable to value of some other variable that doesn't exist at that point at all!

Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Please search this forum for "giveMeJ". This question of forward or not forward referencing has been discussed before.

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: A question on forward referencing.
It's not a secret anymore!