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:

age = 30; // ❌ Error: cannot assign a value to final variable

🧠 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)

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

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *