This week's giveaway is in the Spring forum.
We're giving away four copies of Microservices Testing (Live Project) and have Chris Love & Andres Sacco on-line!
See this thread for details.
Win a copy of Microservices Testing (Live Project) this week in the Spring forum!
  • 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
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

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
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic