• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Final Funda

 
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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;
}
}
 
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yi Meng,
That was was very well explained.
 
Warning! Way too comfortable! Do not sit! Try reading this tiny ad instead:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic