In Java, a final variable can be assigned only once. A final reference can still refer to a mutable object.
A simple example
Use a fixed value
Start withUnit is 3
Do thisMultiply by 2
Result6
Give 3 a name and reuse that name in the multiplication.Main.java
class Main {
public static void main(String[] args) throws Exception {
final int unit = 3;
System.out.println(2 * unit);
}
}
Output
6
Reserve a rehearsal room
The music room can be booked in 30-minute slots. A rehearsal needs three slots, so the calendar sets aside 90 minutes. Naming the slot length lets every booking use the same rule.
Example: #1 - final Variable - Declaration and Initialization
Initialize the final variable and print its value.
Java source code
class Constants {
public static void main(String[] args) {
// Declaration and Initialization of a constant variable
final String str = "Hello World";
// Print the value of a Variable 'str'
System.out.println(str);
}
}
Output
Hello World
Advertisements
Example: #2 - final Variable - Declaration and multiple Initialization
The second assignment to the final variable is a compile-time error.
Java source code
class Constants {
public static void main(String[] args) {
// Declaration of a constant variable
final String str;
// Initialization of a constant variable
str = "Hello World";
// Re-Initialization of a constant variable
// The assignment will throw a compile time error
str = "Hello John";
// Print the value of a constant Variable 'str'
System.out.println(str);
}
}
Compiler error
Constants.java:9: error: variable str might already have been assigned
str = "Hello John";
1 error