Final static variable in Java
Prerequisite : static variables, final keyword
Static variable: When the value of a variable is not varied, then it is a not good choice to go for instance variable. At that time we can add static modifier to that variable. Whenever we declare variable as static, then at the class level a single variable is created which is shared with the objects. Any change in that static variable reflect to the other objects operations. If we won’t initialize a static variable, then by default JVM will provide a default value for static variable.
But when we declare a static variable with final modifier then we should take care of the following conventions:
- Declaring variables only as static can lead to change in their values by one or more instances of a class in which it is declared.
- Declaring them as static final will help you to create a CONSTANT. Only one copy of variable exists which can’t be reinitialize.
Important points about final static variable:
- Initialization of variable Mandatory : If the static variable declared as final, then we have to perform initialization explicitly whether we are using it or not and JVM won’t provide any default value for the final static variable.
class Test {
final static int x;
public static void main(String[] args)
{
}
}
|
Output:
error: variable x not initialized in the default constructor
- Initialization before class loading : For final static variable, it is compulsory that we should perform initialization before class loading completion. We can initialize a final static variable at the time of declaration.
class Test {
final static int x = 10 ;
public static void main(String[] args)
{
System.out.println(x);
}
}
|
Output:
10
- Initialize inside a static block : We can also initialize a final static variable inside a static block because we should initialize a final static variable before class and we know that static block is executed before main() method.
class Test {
final static int x;
static
{
x = 10 ;
}
public static void main(String[] args)
{
System.out.println(x);
}
}
|
Output:
10
Apart from the above mentioned methods, if we try to initialize a final static variable anywhere else then we will get compile time error.
class Test {
final static int x;
public static void m()
{
x = 10 ;
}
public static void main(String[] args)
{
System.out.println(x);
}
}
|
Output:
error: cannot assign a value to final variable x
Implementation of final static variable
class MainClass {
final static String company = "GFG" ;
String name;
int rollno;
public
static void main(String[] args)
{
MainClass ob = new MainClass();
ob.company = "Geeksforgeeks" ;
ob.name = "Bishal" ;
ob.rollno = 007 ;
System.out.println(ob.company);
System.out.println(ob.name);
System.out.println(ob.rollno);
}
}
|
Output:
error: cannot assign a value to final variable company
Last Updated :
22 Sep, 2017
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...