Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From abHilash's java quiz site:
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);
}
}
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 correct answer is:3
I thought 4 is correct. when I compiled and run it gave the output is: 0. Can someone explain why the output is :0?
Thanks
VR

 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
VR,
giveMeJ() is called before j is initialized to 10. Hence the method returns the default value of int which is 0. If you swap the call to the method giveMeJ() with the declaration of j, it will print 10!!
Ajith
 
Baskaran Subramani
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

why sould it take a default value, instead of an assigned value,
eventhough it is assigned after the method call?(if it is able to see the variable declaration,and take the default value, why can't it take the assigned value?)
 
daryl olson
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For a good explanation of what is happening hear see the past thread on this same question:
http://www.javaranch.com/ubb/Forum24/HTML/001464.html
In particular read Prabhu's and Maha Anna's responses.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic