• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static final - compilation fails

 
Garlapati Ravi
Ranch Hand
Posts: 171
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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 ?
 
Jason Irwin
Ranch Hand
Posts: 327
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Ankit Garg
Sheriff
Posts: 9495
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Garlapati Ravi
Ranch Hand
Posts: 171
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot guys!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic