aspose file tools*
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 EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A question on forward referencing." Watch "A question on forward referencing." New topic
Author

A question on forward referencing.

neha kanwal
Greenhorn

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.




Thanks,
Neha
Sanjeev Kulkarni
Greenhorn

Joined: Mar 20, 2006
Posts: 26
Neha,

1)
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!

Cheers!
Sanjeev
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: http://aspose.com/file-tools
 
subject: A question on forward referencing.
 
Similar Threads
Forward referencing
forward referencing
forward refrerences
Abhilash Java Quiz
Forward Referencing to method