Java Constants

Java Tutorial

Java Constants (final)

In Java Constants (final) 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:


 Reassigning is not allowed:


 Final with Methods and Classes (Advanced — For later)

KeywordMeaning
final variableValue cannot be changed
final methodMethod cannot be overridden
final classClass cannot be inherited

Example:


Full Example Program


 


 Summary

FeatureDescription
Keywordfinal
Can change value? No
Naming conventionUPPERCASE
Used forFixed values, security, readability

You may also like...