Understanding Java Constants

In Java, constants are variables whose values cannot be changed once they are assigned. They are declared using the final keyword.

Declaration:

Constants are typically declared using the final keyword, and their names are conventionally written in uppercase with underscores separating words.


final int MAX_SIZE = 100;
final double PI = 3.14159;
final String GREETING = "Hello, World!";

Use Cases:

Constants are commonly used for values that remain constant throughout the execution of a program, such as mathematical constants, configuration settings, or fixed values.


public class Circle {

  // Mathematical constant for pi
  private static final double PI = 3.14159;

  // Instance variable for radius
  private double radius;

  // Constructor
  public Circle(double radius) {
    this.radius = radius;
  }

  // Calculate the area of the circle
  public double calculateArea() {
    return PI * radius * radius;
  }
}

Example:

Here's an example demonstrating the use of constants in Java:


public class ConstantsExample {

  public static void main(String[] args) {
    // Using constants
    final int MAX_VALUE = 100;
    System.out.println("Maximum Value: " + MAX_VALUE);

    final String GREETING = "Welcome!";
    System.out.println(GREETING);
  }
}

Note:

Constants provide a way to give meaningful names to values that should not be changed during the program's execution. By convention, constant names are written in uppercase to distinguish them from regular variables.