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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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();
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: