Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Final member vairable

 
Sandeep Chhabra
Ranch Hand
Posts: 340
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Consider the following code:


Here i am initializing the value of i just before i am using it.
but it gives following compiler error:
--------------------------------------
test41.java:8: cannot assign a value to final variable i
t.i=20;
^
1 error
--------------------------------------

Can anyone tell why?

Moreover if i commment the line :
t.i=20;

than it gives the following error:
--------------------------------------
test41.java:1: variable i might not have been initialized
class test41
^
1 error
--------------------------------------

Is'nt it true that member variables are automatically initialized the default values. then why not final member variables?

Thanx

Sandy
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sandy, I give you a hint (not the solution, but a key to it): Look up "blank final" in the Java Language Specification. Basically, blank finals must have had their values assigned to them by the time the object is constructed.

Have fun!
-Barry
 
Bhaskar Dabbigodla
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Final variable must be initialized before the end of the constructor. In your code there is no user defined constructor. So either you have to initialize it at the line final int i = 7; or you have to add a constructor and initialize it as shown in the followng modified code.



Best Regards,
Bhaskar Dabbigodla
 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Remember Final variables cannot be intialised with default values.

This the reason why it results compliation error.

it is always better to initialised the final variables.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic