• 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
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

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!