Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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".
 
I'm not sure if I approve of this interruption. But this tiny ad checks out:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!