final is a constant whose value can not be changed. So, if a final variable is declared at class level and assigned value there, does it become static as well ?
Do final variables have to be declared at class level only OR can they be declared at local level also ? Does a final variable has to be initialized when its declared or can it be initialized anywhere ?
final and static are completely different things. final means you can't change the value, means declaration and initialization comes in the same place and you can't reinitialize it. it can always be a method local variable as well.
static on the other hand is a class level variable. Declaring a class level variable as final does not make it implicitly static. you have to explicitly mention it as static.
I was also confused when I met real sense of static.
Static variable has always the same value for all instances regardless when instances were created.
Copy paste this code to see static in action:
However I still not always understand when it is good practice to use static method and when to use static inner class?
It would be great if someone explained this too.
nirjari patel wrote:final is a constant whose value can not be changed.
Actually, final has lots of uses; but for a variable, it's a value which can be set precisely once, and after that cannot be changed.
For an instance variable, it can either be set eagerly (ie, with '=') or in a constructor. For a static variable, it is normally initialized eagerly, but you may also be able to set it in a static initializer (don't know because I've never tried it; but I would expect so).
Winston
Post by:autobot
I've read about this kind of thing at the checkout counter. That's where I met this tiny ad:
a bit of art, as a gift, that will fit in a stocking