• 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 ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

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

i=0
j=10;

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

Iam very eager to know,the explanation.


Source:http://www.javaprogrammingworld.com/java-quiz-2.html




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!