• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in Java Puzzlers by Joshua Bloch and Neal Gafter

 
Raj chiru
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21423
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Raj chiru
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Henry Wong
author
Marshal
Pie
Posts: 21423
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic