Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Final Funda Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Final Funda" Watch "Final Funda" New topic
Author

Final Funda

Harvinder Singh
Ranch Hand

Joined: Feb 14, 2003
Posts: 90
/*
When I remove the comment compiler complains:
cannot assign a value to final variable i=10;
^
And when I put the comment then compiler complains:
Variable i might not have been intiallized
Is it necessary to assign the value to a final variable at the same place where
it is declared(then it compiles)???
*/
class ModifierFunda{
final int i=10;

void FinalInit(){
//i=10;
}
}


Hard work beats talent<br />when talent doesn't work hard.<p> - Tim Notke
Yi Meng
Ranch Hand

Joined: May 07, 2003
Posts: 270
Originally posted by Harvinder Singh:
/*
When I remove the comment compiler complains:
cannot assign a value to final variable i=10;
^
And when I put the comment then compiler complains:
Variable i might not have been intiallized
Is it necessary to assign the value to a final variable at the same place where
it is declared(then it compiles)???
*/
class ModifierFunda{
final int i=10;

void FinalInit(){
//i=10;
}
}


You are to make sure that the final variable is only initialized once and only once, and also initialized before constructor returns for non-static final attribute, for static final attribute you are to make sure that it gets initialized before finishing loading the class. That means:
1. non-static final variables:
i. Initialize it when declared. i.e. final int i = 5;
ii. declare it and explicitly initialize it in each constructor. i.e.


2. static final attribute
i. Initialize it when declared. i.e. static final int i = 5;
ii. declare it and explicitly initialize it in a static initializer. i.e.


Meng Yi
Anand Sidharth
Ranch Hand

Joined: Dec 17, 2003
Posts: 44
Yi Meng,
That was was very well explained.
 
Don't get me started about those stupid light bulbs.
 
subject: Final Funda
 
Similar Threads
static final variable initialization inside instance init block
final variable in a for loop
variables in interface
Question from Dan's Exam
variable assignment