It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static initializer order Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static initializer order" Watch "Static initializer order" New topic
Author

Static initializer order

Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
Here is a question from the Whizlabs free trial for SJCP 1.4 exam:



I am confused as to why the answer is 3. The answer indicates that the values of x and y are set to zero. Why wouldn't x be set to 5?
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Take special note of the line in the static initializer:



See the "int" at the beginning of that line? Due to that, we don't assign 5 to the class variable, we create a new local variable and assign 5 to that. The class variable, Static.x is initialized to 0.

Then, to start the main method, we decrement x, taking it to -1.

When we invoke myMethod, we get this:



So, when the assignment is applied x is equal to 1 and y is set to 0.

Finally, back in the main method, we execute this line:



Hopefully, that helps you see why you get the result that you do.


SCJP Tipline, etc.
Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
Ahhh, such a small little word but makes all the difference in the world. Thanks.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static initializer order
 
Similar Threads
a question about static clause
Use of static keyword
Static????????????
static doubt
SCJP Mock Question : static