Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about 'balnk' final fields

 
siv sanny
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


In the above code, I am using final static variable with out initialization. compiler supposed to give errors for such un initialized use of final fields.

But the above code works and o/p is:
printCount: 0
Main: 3

It looks like compiler will not consider un initialized usages in methods. Any further comments on this ?
 
Petrus Pelser
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static class variables are initialized before static code blocks. Because you are using a primitive variable, it initializes to it's default value (0). You are allowed to assign the value only once, but if you do not assign a value on creation, Java will assign the default value - 0 for ints, null for objects, etc.

The compiler will only fail on uninitialized local variables (in methods). All class variables are initialized automatically.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not everybody knows about this, but it is widely understood. Neil Gafter and Josh Block riff on this in Puzzle #49 in "Java Puzzlers." Quoting from that book,


... it is possible to observe a final static field before it is initialized, when it still contains the default value for its type... Final fields are constants only if the initializing expression is a constant expression... in summary, be careful of class initialization cycles.


Note that your variable here does not have a constant expression initializer -- it has no initializer, as appropriate for a blank final.
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The spec says:
It is a compile-time error if a blank final (�4.12.4) class variable is not definitely assigned (�16.8) by a static initializer (�8.7) of the class in which it is declared.


Your variable is assigned by a static initializer, you just access it before that happens.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic