Pages

Saturday, December 18, 2021

Java Final Keyword in Depth for Beginners

1. Overview

In this tutorial, We'll learn how to use the final keyword in java with example programs.

Final is one of the keywords in java and final is used to restrict access to java entities.

Interestingly, the final keyword can be used on variable, method and class levels.

Java Final Keyword

All examples are shown in this article are available on GitHub.


2. What is the Final Keyword in java?


The final keyword in java is a non-access modifier and used to restrict the access of variables, methods or classes.

If any variable is declared as final then its value can not be changed and reassigned with the new values.

If the method is declared as the final method then the method can not be overridden in the subclasses and prevents providing classes own implementations.

If the class is declared as final then the class can be inherited by any other class.

Let us look at each area in detail with examples.


3. Final Variables in Java With Examples

Usage of the final keyword on the variable is allowed in java. This indicates that once the variable is declared as final then its value can not be modified or reassigned.

3.1 Local variable vs Local Final Variable

Look at the simple example which shows the difference between the normal local variable and the final local variable.

Example 1

package com.javaprogramto.keywords.finals;

public class FInalVaraibleExamples {

	public static void main(String[] args) {

		// normal local variable
		int i = 10;
		System.out.println("local i = " + i);

		// final local variable
		final int k = 20;
		System.out.println("final j = "+k);
	}

}

Output

local i = 10
final j = 20


3.2 What happens if the final and normal local value changes?

Let us try to change both local and final variable values.

Example 2


package com.javaprogramto.keywords.finals;

public class FInalVaraibleExamples {

	public static void main(String[] args) {

		// normal local variable
		int i = 10;
		i = 20;
		System.out.println("local i = " + i);

		// final local variable with value reassignment
		final int j = 10;
		j = 20; // compile time error
		System.out.println("final j = " + j);
	}

}


Output

This program did not compile because of final variable value is changed. Because the final variable is considered as constant in java.

How to create constants in java?

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The final local variable j cannot be assigned. It must be blank and not using a compound assignment

	at com.javaprogramto.keywords.finals.FInalVaraibleExamples.main(FInalVaraibleExamples.java:14)


3.3 Create Local Final Variable without assigning value

Do you think is it possible to declare the local variable as final without assigning any value?

Assume, we do not know the value now and that will be given at a later point in time. In such cases, can we declare the final variable not assigning any value?

Example 3


package com.javaprogramto.keywords.finals;

public class FInalVaraibleExamples2 {

	public static void main(String[] args) {

		// final local variable with no value assigned at the time of declaration
		final int j;
		int i = 20;
		
		j = 20; 
		System.out.println("final j = " + j);
	}

}


Output

final j = 20

From the above program, we could see that program was compiled and executed with no errors.

Hence, it is allowed to declare the final local variable without any value and can be assigned with a value later point of time for final local variables.

If the final variable is not initialized with the value at the time of declaration and the value will be assigned later point of time then it is called "Blank Final Variable".

3.4 Applying the final variables on instance variables

We can use the final keyword on the instance variables.

The final instance variable can be initialized with the value at the time of declaration.

If you do not assign the value to it then it must be initialized from the initializer block or constructor.

If any class has multiple constructors then the blank final variable must be initialized from the constructors of the class.

If blank final variables are not assigned with the value at declaration and value is not initialized in constructor or initializer block then we will get the compile-time error.


Example on final instance varaible

package com.javaprogramto.keywords.finals;

public class FInalVaraibleExamples3 {

	final int limit = 3;

	public static void main(String[] args) {

		FInalVaraibleExamples3 fInalVaraibleExamples3 = new FInalVaraibleExamples3();
		System.out.println("limit " + fInalVaraibleExamples3.getLimit());

	}

	public int getLimit() {

		return this.limit;
	}

}


Output

limit 3


Example - Blank final variable + constructor initialization

limit is a regular instance variable but newLimit is a final instance variable without initialization.

newLimit is initialized from the constructor so it will compile and run fine.

package com.javaprogramto.keywords.finals;

public class Customer {

	private int limit;
	private final int newLimit;

	public Customer(int limit, int newLimit) {

		this.limit = limit;
		this.newLimit = newLimit;
	}
	
}

If we remove the constructor from the above example then it will give the compile-time error saying "The blank final field newLimit may not have been initialized".


Example - Blank final variable + initialization block

package com.javaprogramto.keywords.finals;

public class Customer {

	private int limit;
	private final int newLimit;

	{
		newLimit = 100;
	}
	
}


Example - Blank static final variable

If the final instance variable is declared as static then it must be only initialized from the static initializer block


package com.javaprogramto.keywords.finals;

public class Customer {

	private int limit;
	private static final int newLimit;

	static {
		newLimit = 200;
	}
	
}


3.5 Applying the final Reference variables

We can declare StringBuffer or Employee classes as final reference variables.

When we do like this will allow modifying the object values but reference can be reassigned with the new one.

Look at the below code.

package com.javaprogramto.keywords.finals;

public class FInalVaraibleExamples4 {

	public static void main(String[] args) {

		final StringBuffer sb = new StringBuffer("hello");
		
		sb.append(" world");
		
		System.out.println("sb value - "+sb.toString());
	}

}

Modifying the value of the final ref variable is allowed but if we try to reassign the sb with a new StringBuffer object then will give compile time error as below.


// reassigning with new string buffer object which is not allowed on final varaibles.
sb = new StringBuffer(); // compile time error


3.6 When to use final variables in java?

The main difference between the normal and final variables is normal value can be changed as many times as needed but the final variables can not be modified once assigned.

Use java variables as final only if you want to have only assigned value throughout the program remain as same as constant.


4. Final Methods in Java With Examples

The main usage of the final method is to avoid and restrict method access by the subclasses.

And also this prevents providing the unwanted and improper use of definitions of the same method.

For example, create the class Car with the method fogLightsOn(). This method has to on only the fog lights.

And this class has subclasses such as FordCar, HondaCar classes. These two classes can override fogLightsOn() method with different behaviour. So to prevent unwanted behaviours.,

Example

package com.javaprogramto.keywords.finals;

public class FinalMethodExample1 {

	public static void main(String[] args) {

		Car ford = new FordCar();
		ford.fogLightsOn();

		Car honda = new HondaCar();
		honda.fogLightsOn();

	}
}

class Car {

	public void fogLightsOn() {
		System.out.println("Fog lights turned on now");
	}
}

class FordCar extends Car {

	public void fogLightsOn() {
		System.out.println("Lights are turned off");
	}
}

class HondaCar extends Car {

	public void fogLightsOn() {
		System.out.println("Lights are turned off permanently");
	}
}


Output

Lights are turned off
Lights are turned off permanently

In this example, fogLightsOn() method is overridden and provided with different logic rather than turning on fog lights. To avoid unwanted definitions, we have to make the Car.fogLightsOn() method as final as below.


class Car {

	public final void fogLightsOn() {
		System.out.println("Fog lights turned on now");
	}
}


Subclasses will get the compile-time error once the parent method is declared as final.


5. Final Classes in Java With Examples

In java, the final keyword is allowed to use on the class level along with the access modifiers. Usage of final in the class declaration will prevent other classes to extend or inheriting or creating the sub classes.

Final classes in java

If any other class tries to extend it then will get the compile-time error.

Example


final class Java {

	public void sayHelloWorld() {
		System.out.println("hello world");
	}
}

class JavaProgamTo extends Java {

}


Compile time error

The type JavaProgamTo cannot subclass the final class Java


6. Conclusion

In this article, we have seen in-depth about the Java Final keyword. 

The final keyword is used to restrict the changing or reassigning of the final variable.

Final methods restrict to provide the different implementations by subclasses.

The final class restrict other classes to inherit it.

If we try to access or modify them will result in compile time error.

GitHub

Java Final api

How to create immutable class in java?

No comments:

Post a Comment

Please do not add any spam links in the comments section.