aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on Accessmodifiers 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 "Question on Accessmodifiers" Watch "Question on Accessmodifiers" New topic
Author

Question on Accessmodifiers

majohnad majohnad
Greenhorn

Joined: Jan 01, 2003
Posts: 24
In the below question how is the output is 0,
public class AQuestion
{
private int i = giveMeJ();
public int j = 10;
private int giveMeJ()
{
return j;
}
public static void main(String args[])
{
System.out.println((new AQuestion()).i);
}
}


zxjohn
Karthik Veeramani
Ranch Hand

Joined: Dec 22, 2002
Posts: 132
I think this question was already discussed here.
When i gets initialised 1st, though the variable j is recognised, its not yet been assigned to 10. So it has its default value 0.
Others please correct me if im wrong.


Thanks<br />Karthik<br />SCJP 1.4, CCNA.<br /> <br />"Success is relative. More the success, more the relatives."
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
That's correct. Instance variable initializers are invoked in textual order, which means that i will be initialized prior to j. Therefore i ends up being initialized to 0 because j hasn't been initialized yet when i is assigned the value of j. By default, all instance variables have the value 0 (numbers, at least) when they are created.
The use of a method to set the value of i is just a ploy to trick the compiler because, had you used this:

The compiler would complain at you because it's smart enough to realize that you haven't yet initialized j and this is considered a "forward reference."
By putting the method invocation in there, you can trick the compiler into compiling what really boils down to the same code.
I hope that helps,
Corey


SCJP Tipline, etc.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question on Accessmodifiers
 
Similar Threads
Angelfire.com....quiz 2
Angelfire.com....quiz 2
please explain why the compiler is not complaining and why the output is 0
Variable initialization
forward refrerences