my dog learned polymorphism*
The moose likes Beginning Java and the fly likes Doubt in Java Puzzlers by Joshua Bloch and Neal Gafter Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt in Java Puzzlers by Joshua Bloch and Neal Gafter" Watch "Doubt in Java Puzzlers by Joshua Bloch and Neal Gafter" New topic
Author

Doubt in Java Puzzlers by Joshua Bloch and Neal Gafter

Raj chiru
Ranch Hand

Joined: Aug 12, 2008
Posts: 141
Hi Friends,
I could not understand the program execution of the Java Puzzlers of puzzle 49:


when you execute this program it will print Elvis wears a size -1930 belt why?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18765
    
  40

The explanation provided by the book is very detail (and very enlightening, if I may add). What is it about the explanation that is still confusing to you? We can't elaborate on the answer, if you don't tell us what you don't understand about the answer.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Raj chiru
Ranch Hand

Joined: Aug 12, 2008
Posts: 141
Hi Henry,
Thanks For Your Reply,
Actually where I'm confusing is,we are explicitly declared the static field values,right?But why First,static fields are set to default values?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19684
    
  20

Static initializers are executed in declared order. So in this case, INSTANCE is initialized first, then CURRENT_YEAR. However, Elvis needs CURRENT_YEAR but it hasn't been initialized yet. Because the JVM simply does not initialize CURRENT_YEAR right there and then its default value is used.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18765
    
  40

raj chiru wrote:
Actually where I'm confusing is,we are explicitly declared the static field values,right?But why First,static fields are set to default values?


Well, which is worse? A default value or an undefined random value?

From this puzzle, you can see that initialization is not atomic, and it is possible to see variables before they get assigned. So, yes. Static fields are set to default values -- because the values is not known yet. But that is better than an undefined random value, which is what it would be seen as if the variable isn't set.

BTW, there is an exception to this rule. If the static variable is a compile time constant, then the value is guarranteed to be known before it is used -- and it will be set correctly to the compile time constant value.

Henry
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Doubt in Java Puzzlers by Joshua Bloch and Neal Gafter