aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt" Watch "Doubt" New topic
Author

Doubt

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Mar 17, 2000
Posts: 5782
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


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Baskaran Subramani
Ranch Hand

Joined: Jul 30, 2000
Posts: 38

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

Joined: Aug 15, 2000
Posts: 36
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt