Final Instance Variable
- if the value of the variable is varied from object to such type of variable are called the instance variable.
- for every object, a separate copy of the instance variable will be created.
- for instance, the variable we are not required to perform initialize explicitly jvm will always provide default values.
eg-:
class Test{
int x;
public static void main(String... args){
Test t=new Test();
System.out.print(t.x); //output-: 0
}
}
- if the instance variable declare as final then compulsory we have to perform initialization explicitly where we are using are not and jvm won't provide default value.
eg-:
class Test{
final int x;
}
compile time error-: variable x might not have been initialized.
Rule-: for the final instance variable compulsory we should perform initialization before constructor completion.
that is the following are various places for initialization.
- At the time of the instance of declaration.
class Test{
final int x=10;
}
- inside instance block.
eg-:
class Test{
final int x
{
x=10;
}
}
- inside constructor
eg-:
class Test{
final int x;
Test(){
x=10;
}
}
these are only possible places to perform initialization for final instance variables. if we try to perform anywhere else then we will get compile time error.
eg-:
class Test{
final int x;
public static void m(){
x=10;
}
}
compile time error-: cannot assign a value to final variable x
Final Static Variables
if the value of the variable is not varied from object to object such a type of variable are not recommended to declare as instance variables we have to declare those variables at a class level by using a static modifier.
in the case of instance, a variable for every object a separate copy will be created but in the case of static variables, a single copy will be created at class level and shared by every object of that class.
for static variables it's not required to perform initialization explicitly JVM is always provided a default value.
eg-:
class Test{
static int x;
public static void main(String... args){
System.out.print(x); //output is : 0
}
}
if the static variable is declared as a final then compulsory we should perform initialization explicitly otherwise we will get compile time error. and JVM won't provide any default value.
eg-:
class Test{
final static int x;
}
compile time error-: variable x might not have been initialization.
Rule-:for final static variable compulsory we should initialize before class loading completion .
that is the following are various places for this.
- At the time of declaration.
eg-:
class Test{
final static int x=10;
}
- inside the static block.
eg-:
class Test{
final static int x;
static {
x=10;
}
}
these are the only possible places to perform initialization for final static variables if we are trying to perform anywhere else then we will get compile time error.
eg-:
class Test{
final static int x;
public void m(){
x=10;
}
}
compile time error-: cannot assign value to final variable x.
Final Local Variables