← Back to Core Java Course | Chapter 7: OOP Core | Lesson 9 of 11

Java final Keyword

Final Variables

A final variable can be assigned exactly once; after that first assignment, any attempt to reassign it is a compile error. This is Java's way of expressing a true constant at the language level, not just a naming convention.

Example: Final Variables

java
public class Main {
	public static void main(String[] args) {
		final int max = 100;
		System.out.println(max);
		// max = 200; // compile error: reassigning a final variable
	}
}

Blank Final Variables

A blank final variable is declared without an initializer at the point of declaration, but Java still requires it to be assigned exactly once — typically inside every constructor — before the object is considered fully constructed.

Example: Blank Final Variables

java
class Config {
	final int id;
	Config(int id) {
		this.id = id; // must be assigned exactly once, here in the constructor
	}
}
public class Main {
	public static void main(String[] args) {
		Config c = new Config(7);
		System.out.println(c.id);
	}
}

Final Methods

Marking a method final prevents any subclass from overriding it, which is useful when a method implements logic (like a security check or a core algorithm) that must behave identically in every subclass, no exceptions.

Example: Final Methods

java
class Vehicle {
	final void checkSafety() {
		System.out.println("Safety check passed");
	}
}
class Car extends Vehicle {
	// void checkSafety() {} // would not compile: cannot override a final method
}
public class Main {
	public static void main(String[] args) {
		new Car().checkSafety();
	}
}

Final Classes

A final class cannot be extended at all — no subclass can be created from it. String itself is final in the standard library, specifically so that code relying on String's immutability guarantees can't be broken by a malicious or careless subclass.

Example: Final Classes

java
final class Constants {
	static final double PI = 3.14159;
}
// class MoreConstants extends Constants {} // would not compile: Constants is final
public class Main {
	public static void main(String[] args) {
		System.out.println(Constants.PI);
	}
}

Final Parameters

Declaring a method parameter final prevents the method body from reassigning that parameter to a different reference or value, though it says nothing about whether the object the parameter points to can itself be mutated internally.

Example: Final Parameters

java
public class Main {
	static void show(final int x) {
		// x = 10; // would not compile: x is final
		System.out.println(x);
	}
	public static void main(String[] args) {
		show(5);
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.