This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Final member vairable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Final member vairable" Watch "Final member vairable" New topic

Final member vairable

Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
Posts: 340
Consider the following code:

Here i am initializing the value of i just before i am using it.
but it gives following compiler error:
-------------------------------------- cannot assign a value to final variable i
1 error

Can anyone tell why?

Moreover if i commment the line :

than it gives the following error:
-------------------------------------- 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?



Regards<br />Sandy<br />[SCJP 5.0 - 75%]<br />[SCWCD 1.4 - 85%]<br />------------------<br />Tiger, Tiger burning bright,<br />Like a geek who works all night,<br />What new-fangled bit or byte,<br />Could ease the hacker's weary plight?
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
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!

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Bhaskar Dabbigodla

Joined: Aug 02, 2002
Posts: 10
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

Thanks and Regards,<br />Bhaskar Dabbigodla<br />SCJP1.4 (98%)
Karu Raj
Ranch Hand

Joined: Aug 31, 2005
Posts: 479

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.
It is sorta covered in the JavaRanch Style Guide.
subject: Final member vairable