• 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:

variables & values

 
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,
Look at this piece of code
class Test {
private int i = giveMeJ();
private int j = 10;
private int giveMeJ() {
return j;
}
public static void main(String args[]) {
System.out.println((new Test()).i);
}
}
1.Compiler error complaining about access restriction of private variables of AQuestion.
2.Compiler error complaining about forward referencing.
3.No Compilation error - The output is 0;
4.No Compilation error - The output is 10;
The output is 0.
Class variables are initialized after the constructors are called.. So here shouldnt the value of i = 10 ? But it is zero...Why ?
Can anyone explain...
Thx in advance.


 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi aru,
you are correct class variables will be intialised as soon as you call the constructor..here in this case you just observe the forward referencing of method not constructor givemej()...so when you call this method J is not yet intialised ,since it is not defined else where in the constructor,so by the time you call the method,j is still 0(class var automatically intialised)....only after that method call,j is intialised to 10..so the var i will get the value 0 not 10..i am not good at putting good technical words...I hope I am somewhat able to clear your doubt..if I am wrong please feel free to correct me..
thanks
krishna
 
It's just like a fortune cookie, but instead of a cookie, it's pie. And we'll call it ... tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic