Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Final Funda

 
Harvinder Singh
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
/*
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;
}
}
 
Yi Meng
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Anand Sidharth
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yi Meng,
That was was very well explained.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic