BCA / B.Tech 9 min read

Constants in Java

Constants in Java:

A constant is a variable whose value cannot be changed after it has been initialized. In Java, constants are created using the `final` keyword. Once a `final` variable is assigned a value, it becomes read-only.

Declaring a Constant:

You declare a constant by using the `final` keyword before the variable declaration.

final double PI = 3.14159;

By convention, the names of constant variables are written in all uppercase letters, with words separated by underscores (`_`) to improve readability.


Benefits of using Constants:
  • Readability: Using a named constant like `MAX_USERS` makes the code more self-explanatory than a magic number like `100`.
  • Maintainability: If the constant value needs to be changed, you only have to update it in one place.
  • Error Prevention: The compiler will prevent you from accidentally changing the value of a constant.

To create a global constant that is associated with the class rather than an instance, you declare it as `public static final`.