Java Constants (final)
✅ Java Constants (final)
In Java, a constant is a variable whose value cannot be changed once it is assigned.
To declare a constant, you use the final keyword.
📌 Basic Example
If you try to change the value later:
🧠 Why Use Constants?
-
To store fixed values that should not be changed in the program.
-
Improves readability and avoids accidental modification.
🏷 Recommended Naming Convention
Constant names are written in UPPERCASE letters, often with underscores:
✔ Constant with static
Often constants are declared as both:
-
static→ belongs to the class, not objects -
final→ value can’t change
Example:
📍 Final with Strings and Objects
final prevents reassignment — but not modification of internal content (for objects).
Example:
📌 Final with Methods and Classes (Advanced — For later)
| Keyword | Meaning |
|---|---|
final variable |
Value cannot be changed |
final method |
Method cannot be overridden |
final class |
Class cannot be inherited |
Example:
✔ Full Example Program
🔍 Summary
| Feature | Description |
|---|---|
| Keyword | final |
| Can change value? | ❌ No |
| Naming convention | UPPERCASE |
| Used for | Fixed values, security, readability |
