Constants in Java - final keyword
Java offers a placeholder or a container to hold a constant value in a memory location using a built in keyword known as final
in other words constant variable. Once the variable gets initialized, it won't allow us to re-initialize/modify the value.
The main reasons to use the constants are to implement the concept of reusability and ignore the ambiguous code.
Example: #1 - final Variable - Declaration and Initialization
Declare and initialize the variable str in a same statement and finally print the assigned value of a local variable.
Java Input Screen
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);
}
}
Example: #2 - final Variable - Declaration and multiple Initialization
Declare a final variable and then initialize the variable str with the value
"Hello World" and "Hello John" respectively,
finally print the assigned value of local variable. The program will throw a compile time error because the below program
tries to reassign the already assigned variable (i.e. final variable)
Java Input Screen
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);
}
}
Java Output Screen Compiler Error
Constants.java:9: error: variable str might already have been assigned
str = "Hello John";
1 error
BBMINFO