Literally, final variables will mean unable to change the value .final variables/references need to be initialized before they can be used for the first time.

The restriction in Java is that the final member variables need to be initialized before normal usage. There are different valid initialization scenarios depending upon the scope of variable. We shall see different scenario where a final member variable is used as shown below:

Different scopes for initialization

Now we shall see various types of final variables being initialized. The scenarios are supported with corresponding code samples.

Scope is static level:

A static final variable must be initialized before the class loading is complete. When it comes to static, we have static variables and blocks to perform initialization.
This means that a static final variable/reference can be initialized in the following two ways:

static variable initialization

One can initialize the static final variable while declaring only.

	package example.java;

	public class Test{

		static final int a = 10;

		public static void main(String[] args){
			System.out.println(a);
		}
	}

Note: In case of if else, go to and try/catch blocks in the static initializer block, you need to make sure that the static final fields/variables have a valid value when you exit the static block. A code sample for the same is shown below:

static final int a;
static{
    if(b==c){
       a=10;
    } else {
       a=11;
    }
}

If you don’t handle it like that then a compiler error about the uninitialized final variables shall be thrown.

Initialization using static block

or we can also perform initialization of static final variable by using a static initializer block as shown below:

	package example.java;

	public class Test{

		static final int a;

		static {
			a=10;
		}

		public static void main(String[] args){
			System.out.println(a);
		}
	}

The second example code works because:
1) The compiler optimizes the code to merge the initialization and declaration of primitive variable “a”
2) If no optimization happens then also it works because the static code blocks are executed before the class loading completes

Scope is instance level:

An instance level final variable/reference must be initialized before the instantiation is complete.

instance variable initialization

This means that an instance level final variable/reference can be initialized in the following ways:

	Test.java
	package example.java;

	public class Test{

		final int a = 10;

		public static void main(String[] args){
			Test t = new Test();
			System.out.println(t.a);
		}
	}

Initialization using constructor

or we can use following code for performing initialization of non-static final member variables.

	package example.java;

	public class Test{

		final int a;

		public Test() {
			a=10;
		}

		public Test(int b) {
			a=b;
		}

		public static void main(String[] args){
			Test t = new Test();
			System.out.println(t.a);
			t = new Test(20);
			System.out.println(t.a);
		}
	}

We can notice from above that a non-static final variable can be initialized in the constructor. But if a final variable is initialized in the constructor instead of declaration, it needs to be initialized in all the constructors.
If this doesn’t happen then a compiler error is flashed. This ensures that the variable is initialized in every possible way before object creation.

Also if a final variable is initialized in if block of constructor, then it must be initialized in some way by the else part. This is to ensure that the final variable is definitely initialized.

Scope is method level:

The rule with method level final variables is that they have to initialized before first usage. We may either initialize these variable during declaration or after declaring them.
The following code samples depict both cases:

local variable initialization

	package example.java;

	public class Test{

		public static void main(String[] args){

			final int a = 10;
			System.out.println(a);
		}
	}

Initialization before usage

The following code sample initializes method level final variable after declaration:

	package example.java;

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

The second example code also works because the condition that the final variable has to be initialized before its first use is met in the above code.

Interview Questions

Some of the interview questions related to final variable asked in Java interview are:

  • 1) When will you use final variables in your code?
    Ans: The most common use of final variables is to declare constants. We usually have a separate class containing all the constants used by the application.
    Another use of final variable is with multi-threaded applications where no thread can modify the value of final variable and hence there is no need for synchronized blocks to make sure that there are no dirty read/write operations. This use of final variables helps in improving the performance of multi-threaded applications.
  • 2) How does final variables behave with local inner classes?
    Ans: A method level inner class can not refer to non-final variables of the methods including arguments accepted by the method. To access arguments in local inner class, we need to mark arguments as final.
  • 3) How will you create an immutable class? What role do final variables play in an immutable class?
    Ans: Immutability has its own multi-thread related advantages and to create an immutable class, we need to ensure that the properties of the class don’t get modified in any way. final keyword is used in immutable classes to make sure that properties once initialized by the constructor can’t be changed later on.
  • 4) What will happen if instead of changing the reference of a final variable, we try to modify the value of the variable/object referred to by the final reference? For e.g final Book b = new Book(“abc”); b.changeTitle(“xyz”);
    Ans: Changing the value of the object/data referred to by a final reference is not an issue and will not generate any kind of compiler error or runtime exception.
  • 5) Apart from final keyword being used with variables, where else can we use the final keyword?
    Ans: We can use the final keyword with variables, classes and methods. A final class can’t be sub-classed and a final method can’t be overridden.
  • 6) I want to forcefully change the value of a final reference variable, how can I do that?
    Ans: We can change the values of final reference variables by using reflection. In fact even if the reference variable is marked as private final, it can be changed.

References

1. Changing private final fields via reflection
2. Initializing final variables in Java
3. Final Variables

Initializing final variables in Java admin Core Java
Literally, final variables will mean unable to change the value .final variables/references need to be initialized before they can be used for the first time. The restriction in Java is that the final member variables need to be initialized before normal usage. There are different valid initialization scenarios depending...
<p>Literally, final variables will mean unable to change the value .final variables/references need to be initialized before they can be used for the first time. The restriction in Java is that the <a href="http://www.javaexperience.com/java-best-practice-avoid-final-for-tdd/">final member variables need to be initialized before normal usage</a>. There are different valid initialization scenarios depending upon the scope of variable. We shall see different scenario where a final member variable is used as shown below: <div id="toc"> 1. <a href="#staticscope">Scope is static level</a> 2. <a href="#instancescope">Scope is instance level</a> 3. <a href="#methodscope">Scope is method level</a> 4. <a href="#interviewques">Interview Questions</a> 5. <a href="#references">References</a> </div> </p> <h1>Different scopes for initialization</h1> <p>Now we shall see various types of final variables being initialized. The scenarios are supported with corresponding code samples.</p> <a name="staticscope"></a> <h2>Scope is static level:</h2> <p>A static final variable must be initialized before the <a href="http://www.javaexperience.com/java-class-loading/">class loading</a> is complete. When it comes to static, we have static variables and blocks to perform initialization. This means that a static final variable/reference can be initialized in the following two ways: </p> <h3>static variable initialization</h3> One can initialize the static final variable while declaring only. 1 <strong>Note:</strong> In case of if else, go to and try/catch blocks in the static initializer block, you need to make sure that the static final fields/variables have a valid value when you exit the static block. A code sample for the same is shown below: 1 If you don't handle it like that then a compiler error about the uninitialized final variables shall be thrown. <h3>Initialization using static block</h3> or we can also perform initialization of static final variable by using a static initializer block as shown below: 1 <p>The second example code works because: 1) The compiler optimizes the code to merge the initialization and declaration of primitive variable “a” 2) If no optimization happens then also it works because the static code blocks are executed before the class loading completes </p> <a name="instancescope"></a> <h2>Scope is instance level:</h2> <p>An instance level final variable/reference <a href="http://www.javaexperience.com/java-best-practice-avoid-final-for-tdd/">must be initialized before the instantiation</a> is complete. <h3>instance variable initialization</h3> This means that an instance level final variable/reference can be initialized in the following ways: </p> 1 <h3>Initialization using constructor</h3> or we can use following code for performing initialization of non-static final member variables. 1 <p> We can notice from above that a non-static final variable can be initialized in the constructor. But if a final variable is initialized in the constructor instead of declaration, it needs to be initialized in all the constructors. If this doesn't happen then a compiler error is flashed. This ensures that the variable is initialized in every possible way before object creation. Also if a final variable is initialized in if block of constructor, then it must be initialized in some way by the else part. This is to ensure that the final variable is definitely initialized. </p> <a name="methodscope"></a> <h2>Scope is method level:</h2> <p>The rule with method level final variables is that they have to initialized before first usage. We may either initialize these variable during declaration or after declaring them. The following code samples depict both cases:</p> <strong>local variable initialization</strong> 1 <h3>Initialization before usage</h3> The following code sample initializes method level final variable after declaration: 1 <p>The second example code also works because the condition that the final variable has to be initialized before its first use is met in the above code.</p> <a name="interviewques"></a> <h2>Interview Questions</h2> Some of the interview questions related to final variable asked in Java interview are: <ul> <li>1) When will you use final variables in your code? <strong>Ans:</strong> The most common use of final variables is to declare constants. We usually have a separate class containing all the constants used by the application. Another use of final variable is with multi-threaded applications where no thread can modify the value of final variable and hence there is no need for synchronized blocks to make sure that there are no dirty read/write operations. This use of final variables helps in improving the performance of multi-threaded applications.</li> <li>2) How does final variables behave with local inner classes? <strong>Ans:</strong> A method level inner class can not refer to non-final variables of the methods including arguments accepted by the method. To access arguments in local inner class, we need to mark arguments as final.</li> <li>3) How will you create an immutable class? What role do final variables play in an immutable class? <strong>Ans:</strong> Immutability has its own multi-thread related advantages and to create an immutable class, we need to ensure that the properties of the class don't get modified in any way. final keyword is used in immutable classes to make sure that properties once initialized by the constructor can't be changed later on.</li> <li>4) What will happen if instead of changing the reference of a final variable, we try to modify the value of the variable/object referred to by the final reference? For e.g final Book b = new Book("abc"); b.changeTitle("xyz"); <strong>Ans:</strong> Changing the value of the object/data referred to by a final reference is not an issue and will not generate any kind of compiler error or runtime exception.</li> <li>5) Apart from final keyword being used with variables, where else can we use the final keyword? <strong>Ans:</strong> We can use the final keyword with variables, classes and methods. A final class can't be sub-classed and a final method can't be overridden.</li> <li>6) I want to forcefully change the value of a final reference variable, how can I do that? <strong>Ans:</strong> We can change the values of final reference variables by using reflection. In fact even if the reference variable is marked as private final, it can be changed.</li> </ul> <a name="references"></a> <h2>References</h2> 1. <a href="http://stackoverflow.com/questions/4516381/changing-private-final-fields-via-reflection" target="_blank">Changing private final fields via reflection</a> 2. <a href="http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection" target="_blank">Initializing final variables in Java</a> 3. <a href="http://enos.itcollege.ee/~jpoial/docs/tutorial/java/nutsandbolts/finalVariables.html" target="_blank">Final Variables</a>
The following two tabs change content below.
I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database. Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post. Thanks for the support.