It's not a secret anymore!
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 OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "about Watch "about New topic

about 'balnk' final fields

siv sanny

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

Joined: Jul 08, 2003
Posts: 24193

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 -
if (Posts < 30) JavaRanchFAQ);
I agree. Here's the link:
subject: about 'balnk' final fields
jQuery in Action, 3rd edition