Java final Keyword Examples

Filed Under: Java
Java Final Keyword

The final keyword in Java can be used with variables, methods, and classes.

  1. Final Variables: When we mark a variable as final, we can’t reassign its value.
  2. Final Class: When a class is final, we can’t extend it.
  3. Final Method: We can’t override a final method.

Let’s look into the final keyword in more details.

Recommended Read: Java Keywords

1. Final Variables

Java allows us two ways to create a variable and assign some value to it.

  1. We can declare a variable and assign the value later on.
  2. We can declare the variable and assign the value in the same statement using the assignment operator.

Let’s look at the usage of final variables for both the scenarios.


package com.journaldev.examples;

public class Config {

	final static String NAME = "CONFIG";

	final long initTime;

	Config() {
		this.initTime = System.currentTimeMillis();
	}

	public static void main(String[] args) {
		Config cfg1 = new Config();
		System.out.println(cfg1.initTime);

		Config cfg2 = new Config();
		System.out.println(cfg2.initTime);

		// The final field Config.NAME cannot be assigned
//		Config.NAME = "config";

		// The final field Config.initTime cannot be assigned
//		cfg1.initTime = 1L;
	}
}

1.1) Java Final Variables are Constant?

Since we can’t reassign a new value to the final variable, they look like constant. But, it depends on the type of the final variable.

If the final variable data type is immutable, such as primitives and String, then the final variable will remain constant.

If the final variable data type is mutable, we can call the methods to change the object state. In this case, the final variable is not constant as it can be changed.

Let’s understand this with a simple example.


package com.journaldev.examples;

public class FinalExamples {

	// data types are immutable
	final static int COUNT = 10;
	final static String NAME = "FinalExamples";
	
	// data types are mutable
	final static StringBuilder SB = new StringBuilder();
	
	public static void main(String[] args) {
		SB.append("Hello");
		System.out.println(SB.toString());
		
		SB.append("Java");
		System.out.println(SB.toString());

	}
	
}

1.2) Local Final Variables

When a final variable is created inside a method, it’s called a local final variable.


void foo(int[] ints) {
	final int x = 10;
	final boolean flag;
	flag = true;

	for (final int i : ints) {
		System.out.println(i);
	}
}

We are able to use the final keyword in the enhanced for loop because when the for loop iteration is finished, a new variable is created every time. The same is not true with the normal for loop, so the below code will throw compile-time error.


// The final local variable j cannot be assigned. 
// It must be blank and not using a compound assignment
for(final int j = 0; j< ints.length; j++) {
	System.out.println(j);
}

2. Final Class

When a class is declared as final, we can't extend it. It's called a final class. The perfect example of the final class in JDK is the String class.

If you have to create an immutable class, you have to mark it as a final class.


final class SecureAccess{
	
}

//compile time error
//class MoreSecureAccess extends SecureAccess {}
Java Final Class

Java Final Class

3. Final Methods

When a method is marked as final, it's called a final method. A final method can't be overridden in the subclass. For example, Object class wait() and notify() methods are final and we can't override them in our implementation classes.

Overloading is allowed for the final methods. Let's look at an example of final methods in Java.


package com.journaldev.examples;

public class Base {
	
	final void foo(int i) {}
	
	//overloading is allowed
	void foo(int i, String s){}
}

class Child extends Base{
	
	@Override
	void foo(int i, String s) {}
	
	@Override
	// void foo(int i) {}
}
Java Final Method

Java Final Method

4. When to use final keyword in Java?

  • We can use final keyword to define some class level constants.
  • Create final variables for objects when you don't want them to be changed, such as Object specific properties that we can use for logging purposes.
  • If you don't want the class to be extended, mark it as final.
  • If you are creating an immutable class, you have to make it a final class.
  • If you want the method implementation to remain same for all the subclasses, mark them as a final method.

5. References

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages