• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

A basic question..

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Please take a look at the code below:
public class Test
{
private int i = getJ();
private int j = 10;
private int getJ()
{
return j;
}
public static void main(String[] args)
{
System.out.println(new Test().i);
}
}

will print 0.
How is it possible? Anyone could please explain this?
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi nikita
I think this is a case of forward referencing.
So here compiler doesn't know that get is existing. So it cannot initialize. But still it is showing 0 because all the object members are initialized to binary zero when an object is created.
Hence you are getting 0.
murali
 
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by mmkris_1:
hi nikita
I think this is a case of forward referencing.
So here compiler doesn't know that get is existing. So it cannot initialize. But still it is showing 0 because all the object members are initialized to binary zero when an object is created.
Hence you are getting 0.
murali


If you modify the code slightly to be
public class Test1
{
private int j = 10;
private int getJ()
{
return j;
}
private int i = getJ();
public static void main(String[] args)
{
System.out.println(new Test1().i);
}
}
The output is 10
if you modify the code to be
public class Test1
{
private int j = 10;
private int i = getJ();

private int getJ()
{
return j;
}
public static void main(String[] args)
{
System.out.println(new Test1().i);
}
}
The output is still 10!
It isn't that it can't call the method to initialize the variable, it's the order that operations occur. In your example, when i is intialized to getJ(), the value of j is still the default value of 0.

[This message has been edited by Carl Trusiak (edited June 20, 2000).]
 
What? What, what, what? What what tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic