Constants
In Java, constants are variables whose values cannot be changed once assigned. These are typically used to represent fixed values that are meant to remain the same throughout the execution of a program. Constants in Java are declared using the final
keyword. When you mark a variable as final
, its value can only be assigned once, and after that, it cannot be modified.
Characteristics of Constants in Java
- Immutable: Once assigned, the value cannot be changed.
- Naming Convention: By convention, constants are written in uppercase letters with words separated by underscores (e.g., MAX_SIZE, PI).
How to Declare Constants
- Primitive Constants:
final int MAX_SIZE = 100;
final double PI = 3.14159;
- Constant Objects: Even though the object reference can be marked as
final
, the object itself may still be mutable (modifiable). Thefinal
keyword ensures the reference cannot be reassigned to another object.
final String APP_NAME = "MyApplication";
Usage Example
public class Example {
public static final double PI = 3.14159;
public static void main(String[] args) {
System.out.println("The value of PI is: " + PI);
}
}
In this example, PI
is a constant, and it cannot be changed anywhere in the code.
Last updated on