This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static final - compilation fails Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static final - compilation fails" Watch "static final - compilation fails" New topic
Author

static final - compilation fails

Garlapati Ravi
Ranch Hand

Joined: Mar 05, 2008
Posts: 171

got compilation error:
Test.java:3: cannot assign a value to final variable i
Test(){i=0;}

But below two snippets works fine:


Can anyone explain why it's failing in first case ?


Ravi Kumar
SCWCD 5 - 89%, SCJP 1.4 - 90%
Jason Irwin
Ranch Hand

Joined: Jun 09, 2009
Posts: 327
It is because it it static and final in the first case.

static - class level instance, no constructor will run
final - once initialised cannot be changed. Can be initialized at declaration, in a code block or in a constructor.

In the case of your static final, the constructor runs as part of the object instance, that cannot assign a value to a final that is at the class instance (i.e. static). That "final" already exists and is considered to have been initialised already.

There is a further wrinkle in your code. A static final must be initialised at declaration or in a static code block otherwise you will get a "May not have been intialised" exception during compilation. You'll see that if you comment out the line in your constructor.

So a quick summary:
static - any code block or instance constructor or method can set this so long as it has access
final - must be initialised at declaration, in a code block or in an constructor. Once initialised, it cannot be changed.
static final - must be initialised at declaration, or in a static code block. Once initialised, it cannot be changed (and that includes instance constructors).


SCJP6
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9307
    
  17

The answer is pretty simple, since in the first case, i is a static final field, so you need to assign it a value with the declaration or in a static initializer block



static fields are initialized when the class is loaded while the constructor is run when an instance of the class is created. Since final fields don't get a default value, so you need to assign i a value at the time of class loading...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Garlapati Ravi
Ranch Hand

Joined: Mar 05, 2008
Posts: 171
Thanks a lot guys!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static final - compilation fails