This week's book giveaway is in the Python forum.
We're giving away four copies of Python Continuous Integration and Delivery and have Moritz Lenz on-line!
See this thread for details.
Win a copy of Python Continuous Integration and Delivery this week in the Python 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
  • Devaka Cooray
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Tim Holloway
  • Claude Moore
  • Stephan van Hulst
  • Winston Gutkowski
  • Carey Brown
  • Frits Walraven

Please explain this  RSS feed

Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

In the foloowing question,I expected o/p as "10",but actual o/p is "0".

Where did I go wrong?

Thought deeply,before answering this and concluded answer as '10",but actual o/p is "0".(Tried on my machine too).

Because when 'Aquestion" class is instantiated with "new",its instance variables values are as follows


so when line 1 is executed "giveMeJ" returns "10" and thus,i also should contain "10" right?

Iam very eager to know,the explanation.


public class AQuestion{
private int i = giveMeJ();
private int j = 10;
private int giveMeJ(){
return j;
public static void main(String args[]){
System.out.println((new AQuestion()).i);//line 1
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vatsalya,

All instance variables will initially take on their default values (0 for int variables) when they're created. If you provided any of the instance variables with initializer expressions/values, the variables will then be initialized in the order that you wrote them in your code (along with any initializer blocks).

So basically what happens in this program is that when the initializer in "i = giveMeJ();" is processed, the "j = 10" line hasn't been processed yet. So j still has its default value (i.e. 0) at the time of the giveMeJ() method call.

If you reverse the order of your i and j declarations, you'll get the output you expect. In other words:
will produce the output "10".
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!