Constants in Java
2 min read ·
A constant is a variable whose value cannot be changed once assigned.
In Java, constants are created using the
final keyword.final Keyword
When a variable is declared as
final, its value cannot be modified after initialization.Example:
Once
MAX_USERS is assigned 100, it cannot be changed.final with Different Data Types
Constants are useful when values should never change, such as configuration values.
Naming Convention for Constants
By convention, constant names:
- Are written in uppercase
- Use underscore to separate words
Correct:
Not recommended:
Using uppercase makes constants easily identifiable in large programs.
Final with Objects
When
final is used with objects, the reference cannot change, but object data can still be modified.The reference
sb cannot point to another object, but its content can change.