CONSTANTS

In Java, constants are variables whose values cannot be changed once they have been assigned. They are typically used to store fixed values that are used throughout a program, such as mathematical constants, configuration values, or other unchanging data.

Defining Constants

Constants in Java are defined using the final keyword. The final keyword ensures that the variable can be assigned only once. By convention, constant names are written in uppercase letters with underscores separating words.

1. Declaring Constants

To declare a constant, use the final keyword followed by the type of the variable, the variable name, and the value. Constants can be declared at different levels, such as within a class, an interface, or a method.

Example of Declaring a Constant

public class ConstantsExample {
    // Class-level constants
    public static final double PI = 3.14159;
    public static final String APP_NAME = "MyApplication";

    public static void main(String[] args) {
        // Local constant
        final int MAX_USERS = 100;

        // Use the constants
        System.out.println("Value of PI: " + PI);
        System.out.println("Application Name: " + APP_NAME);
        System.out.println("Max Users: " + MAX_USERS);

        // Uncommenting the following line would cause a compilation error
        // PI = 3.14; // Error: cannot assign a value to final variable PI
    }
}

2. Using Constants in a Program

Constants are typically used for values that are meant to remain unchanged throughout the life of a program, such as configuration values, default settings, or fixed mathematical values.

Example of Using Constants

public class Circle {
    // Define a constant for PI
    public static final double PI = 3.14159;

    // Method to calculate the area of a circle
    public static double calculateArea(double radius) {
        return PI * radius * radius;
    }

    public static void main(String[] args) {
        double radius = 5.0;
        double area = calculateArea(radius);
        System.out.println("Area of the circle: " + area);
    }
}

3. Benefits of Using Constants

4. Constants in Interfaces

In Java, all variables declared in an interface are implicitly public, static, and final. This means they are constants by definition.

Example of Constants in an Interface

public interface AppConfig {
    String APP_NAME = "MyApplication";
    int MAX_USERS = 100;
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Application Name: " + AppConfig.APP_NAME);
        System.out.println("Max Users: " + AppConfig.MAX_USERS);
    }
}