• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

A question on forward referencing.

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please search this forum for "giveMeJ". This question of forward or not forward referencing has been discussed before.
 
Well THAT's new! Comfort me, reliable tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic