Forums Register Login

Is final variable implicitly static ?

+Pie Number of slices to send: Send
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 ?

Thanks
+Pie Number of slices to send: Send
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.

+Pie Number of slices to send: Send
Read what the language specification has to say: http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4
+Pie Number of slices to send: Send
 

Swastik Dey wrote:final means you can't change the value, means declaration and initialization comes in the same place


Nope. Go through the link posted above ^^^
+Pie Number of slices to send: Send
Sorry about that, I was bit wrong in explaining. My idea was to mention re initialization is not allowed.
+Pie Number of slices to send: Send
Hello!

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.
+Pie Number of slices to send: Send
 

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
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
https://gardener-gift.com


reply
reply
This thread has been viewed 991 times.
Similar Threads
Facing null pointer exception in static initialization
Aquestion about type of variable
static modifier
final static variable
Pl Validate the points
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 00:05:07.