aspose file tools*
The moose likes Java in General and the fly likes about 'balnk' final fields Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "about Watch "about New topic
Author

about 'balnk' final fields

siv sanny
Greenhorn

Joined: Jan 03, 2005
Posts: 8


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

Joined: Feb 20, 2006
Posts: 132
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

Joined: Jul 08, 2003
Posts: 24166
    
  30

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.


[Jess in Action][AskingGoodQuestions]
Bill Shirley
Ranch Hand

Joined: Nov 08, 2007
Posts: 457
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.


Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
 
Don't get me started about those stupid light bulbs.
 
subject: about 'balnk' final fields
 
Similar Threads
Final Modifier
final variable initialisation(simple code)
Object initialization sequence
Static final fields and final fields
Enum Constructor doesn't access non-final static variable