final variable in Java

The final variable is the most important concept in java. Most of the programmers may know about the final variable. Here we will discuss What is final variable and final reference variable. How many ways to initialize it.

Here is the table content of the article we will cover this topic.
1. What is the final variable in Java?
2. How to declare a final variable?
3. Initialization of the final variable?
i) Initialization while declaration?
ii) Initialization with the constructor?
iii) Initialization with a static block?

4. Re-assign value to a final variable?
5. Local Java final variable?
6. final with a reference variable?
7. final with an array variable?

8. What is the blank final variable in java?
9. RULES to initialize the blank final variable in the constructor?
10. Real-life example?
11. Why we use the blank final variable?

12. static final in java?
13. final reference variable?

What is the final variable in Java?

When we are using the final keyword with variable it means we are declaring a constant. In java, final variables are just like constants. If you want to make any constant variable, then use the final keyword with the variable.

1. If you are using a final keyword with primitive types of the variable (int, float, char, etc) then you can’t change the value of a final variable once it is initialized. So, we should initialize it.

2. If you are using a final keyword with non-primitive variables (By means of non-primitive variables are always references to objects in Java), the member of the object can be changed. It means we can change the properties of the object, but we can’t change to refer to any other object. We will discuss it separately in a final reference variable.

Firstly we will see how to use the final keyword with the primitive data type. You can’t change the value of final variable after initialization. If you try to change the value of the final variable then the compiler will throw an exception at compile time.

How to declare a final variable

To declare a final variable we need to take care of two things, One declares with the final keyword and another is the initialization of the variable. It is not mandatory to initialize a final variable at the time of declaration. We can initialize it by constructor we will discuss it separately in detail. If you are not initializing it at the time of declaration, it’s called a blank final variable.

final dataType variableName = value;

Here final is a keyword that indicates the JVM to treat this variable as the final variable.
dataType is type of variable which you want to create.
varaibleName is the name of the variable which you want to create.

final int a = 5;
class FinalVariable
{
	public static void main(String args[])
	{
		final int a = 10;
		a = 10+5;
		System.out.println(a);
	}
}

Output: Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The final local variable a cannot be assigned. It must be blank and not using a compound assignment at FinalVariable.main(FinalVariable.java:8)

Initialization of final variable

In Java, the JVM especially takes care of the initialization of the final variable. We must initialize the final variable with a value, otherwise, the compiler will throw compile-time error. But as we have seen in the above example a final variable can only be initialized once.

Java provides three ways to initialize a final variable :
i) Initialization while the declaration
ii) Initialization with the constructor

iii) Initialization with a static block

i. Initialization while the declaration

We can initialize a final variable at the time of the declaration. This approach is common for initialization. If final variables are not initialized at the time of declaration, then it is called a blank final variable. But always remember if the final variable is not initialized at the time of declaration then it must be initialized by another way, otherwise, JVM throws the exception at compile time. We have already seen it in the above example.

ii. Initialization with the constructor

By the use of a constructor, we can initialize the blank final variable. We can initialize a final variable by the constructor. Some programmers misunderstood this concept and think a constructor can initialize the final variable multiple times which is not true. Whenever a constructor invokes by JVM it will create a new object and initialize the value of the new object.

class BlankFinalWithConstructor 
{ 
    // It is a blank final variable
    final int a; 
    BlankFinalWithConstructor()
    {
    	// If we remove this line, we get compiler error. 
    	a = 2;
    }
    
     BlankFinalWithConstructor(int x) 
    { 
        // If we remove this line, we get compiler error. 
        this.a = x; 
    } 
} 
  

class MainClass 
{ 
    public static void main(String args[]) 
    { 
    	BlankFinalWithConstructor object = new BlankFinalWithConstructor();
    	System.out.println("Value of final variable a = "+ object.a);
    	
    	BlankFinalWithConstructor object1 = new BlankFinalWithConstructor(5); 
    	System.out.println("Value of final variable a = "+ object1.a);
  
    	BlankFinalWithConstructor object2 = new BlankFinalWithConstructor(10); 
    	System.out.println("Value of final variable a = "+ object2.a);
    } 
}

Output:
Value of final variable a = 2
Value of final variable a = 5
Value of final variable a = 10

iii. Initialization with a static block

You can initialize a final variable in static block, but it should be static also. But static final variables can’t be assigned value in the constructor. So, they must be assigned a value with their declaration.

class BlankFinalWithConstructor 
{ 
    // It is a blank final variable
    static final int a; 
    static int b;
    static
    {
    	// assigning value to final variable
    	a = 5;
    	b = 8;
    }
   
} 

class MainClass 
{ 
    public static void main(String args[]) 
    { 
    	System.out.println("Value of final variable a = "+ BlankFinalWithConstructor.a);
    	System.out.println("Value of final variable b = "+ BlankFinalWithConstructor.b);
    } 
}

Java final variable: A normal variable can re-assign the value, but the final variables can’t change the value once assigned it. It will remain constant throughout the execution of the program. Hence final variables must be used only for the values that we want to remain constant.

Re-assign value to a final variable

A final variable cannot be reassigned, doing it will throw compile-time error.

class MainClass 
{ 
	 // It is a blank final variable
		final int a = 5; 
		public void setValue()
		{
			a = 10;
		}
    public static void main(String args[]) 
    { 
    	MainClass obj = new MainClass();
    	obj.setValue();
    	System.out.println("Value of a = "+ obj.a);
    } 
}

Output: Exception in thread “main” java.lang.Error: Unresolved compilation problem: The final field MainClass.a cannot be assigned at MainClass.setValue(MainClass.java:9) at MainClass.main(MainClass.java:14)

Local Java final variable

You can create a final variable is inside a method/constructor/block. It must initialize once where it is created.

class MainClass 
{ 
    public static void main(String args[]) 
    { 
    	// It is a local final variable
    	final int a = 5; 
    	System.out.println("Value of a = "+ a);
    } 
}

Output: Value of a = 5

final with a reference variable

If a reference variable of an object is final, then this final variable is called reference final variable. As you know that a final variable cannot be re-assign. In referenced final variable you can changes/reassign the value of its variables. But you can re-assign the reference final variable.

class FinalWithReference 
{
	int a = 5;
}
class MainClass 
{ 
    public static void main(String args[]) 
    { 
    	final FinalWithReference obj = new FinalWithReference();
    	obj.a = 10;
    	System.out.println("Value of a = "+ obj.a);
          // You can't re-assign it. it will throw compilation error
    	//obj = new FinalWithReference();
    } 
}

Output: Value of a = 10

final with array variable

We can create an array variable as final. We can’t re-assign the array variable reference. But we can change the elements of the array.

Example:

class MainClass 
{ 
    public static void main(String args[]) 
    { 
    	final int arr[] = {1, 2, 3};  
        arr[0] = 10;
        arr[1] = 20;
        arr[2] = 30;
        for(int i = 0; i < 3 ; i++ )
        {
        	System.out.println(arr[i]);
        }
    	
        // You can't re-assign it. it will throw compilation error
       // arr = new int[5];
        
    } 
}

Output:
10
20
30

2 thoughts on “final variable in Java”

  1. I think this is one of the most vital info for me. And i’m
    glad reading your article. But wanna remark on few general things, The web site style is ideal, the articles is really nice : D.

    Good job, cheers

    Reply

Leave a Comment