misty dark cloudy desert with snow bridge

1.8 Java | Named Constants

A Named Constant is an identifier that represents a permanent value. The value of a variable may change during the execution of a program; but a Named Constant (or just Constant) represents permanent data that never changes (for example, π is a constant) depending on the type of Java “constant”.

Final vs. Static Final

There are 2 types of Java “constants”. final and static final. The syntax for declaring the lone final constant is:

final datatype CONSTANTNAME = value;

The lone final constant only forces a variable value to be permanent in a single class instance.

The syntax for declaring static final is:

static final datatype CONSTANTNAME = value;

The constants static final forces a variable value to be permanent in all class instances.

Example

A Java named constant can be declared and initialized in the same statement or in separate statements. The word final is a Java keyword for declaring a constant. For example:

import java.util.Scanner; // Scanner is in the java.util package

public class ComputeAreaWithConstant {
    public static void main(String[] args) {
        final double PI = 3.14; // Declare a constant
        
        // Make a Scanner Object
        Scanner input = new Scanner(System.in);
        
        // Prompt the user to enter a radius
        System.out.print("Enter a number for radius: ");
        double radius = input.nextDouble();
        
        // Compute area
        double area = radius * radius * PI;
        
        // Display results
        System.out.println("The area for the circle of radius " + radius + " is " + area);
    }
}

Let’s say that in the above example you add the statement:

double PI = 5.56;

to re-assign the value of PI. But the benefit of using the constant declaration final is that the Java program will not allow you to change the value of a constant:

Java final declaration reuse constant error

Another benefit is that you only have to change the value of the constant from a single location.


What's Your Opinion?