Final modifier is used in a member variable to declare constants. Static modifier when declared says that there is only one copy of the variable shared across the instances.
Yes, but declaring a variable static and non-final (no such keyword) means that the variable value could still be changed, right ?
Are you asking if all final variables shouldn't be by default static too ?
Joined: Sep 28, 2004
Just got confused , yep it's clear now.Thanks dude.
I have one more question.
On declaring a variable as static & final with out initilizing it a value like this.
It gets automatically initilized to "0" [ Exclude the "" ], but a non static final variable doesn't, a developer is allowed to initilize it before the C'tor ends. Is there any specific reason for this default initilization behaviour in case of "static final "variable.
The main difference between a blank final instance variable and a blank final static variable is that a blank final instance variable can be initialized by an initializer block or a constructor while a blank final static variable can only be initialized by a static initializer block.
It is true that a blank final variable has a default value before it is initialized. This can be seen by printing the variable before initializing it but after the declaration appears in the source code. Nonetheless, the blank final variable must be initialized or you get a compiler error.
From the Java Language Specifications:
22.214.171.124 final Fields A field can be declared final (�4.5.4). Both class and instance variables (static and non-static fields) may be declared final.
It is a compile-time error if a blank final (�4.5.4) class variable is not definitely assigned (�16.7) by a static initializer (�8.7) of the class in which it is declared.
A blank final instance variable must be definitely assigned (�16.8) at the end of every constructor (�8.8) of the class in which it is declared; otherwise a compile-time error occurs.