This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Final member vairable

 
Sandeep Chhabra
Ranch Hand
Posts: 340
  • 0
  • 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
  • 0
  • 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
  • 0
  • 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
  • 0
  • 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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic