Constants in Java

Java language has a reserved word const intended for future use. However this keyword was never implemented and has no function. The original intent of the const keyword was to implement readable only references (which means a const reference cannot be used to modify object instance). However Java language designers decided NOT to implement this keyword.

Java however supports read only references using the final keyword. When you declare a variable as final, the variable itself cannot be reassigned to point to another instance. The default coding standard in Java for constants is to use upper case words separated with underscores.

Usually Java programmers define all the constants in the program in a single interface as public static final variables. However this is considered as a bad practice.

public interface MyConstants {

    public static final int NUMBER_OF_MONTHS = 12;
    public static final String DATE_FORMAT = "dd/mm/yyyy";
}

The variable is public so that it can be accessed from anywhere. It is static so that it can be accessed without an instance. It is declared as final and hence the value cannot be changed.

A better approach to defining constant values is to define it in the class which is the most suitable location for the constant. For example, the above interface can be removed and the constants can be moved to its appropriate classes,

public class MyCalendar {
    public static final String DATE_FORMAT = "dd/mm/yyyy";
    // Other Calendar data and methods here
}

An important thing to note here is that final  indicates that the variable cannot be assigned to another instance. However you can modify the instance itself. The final keyword doesn't make the object instance immutable. The following code is perfectly valid,

public static final Circle MY_CIRCLE = new Circle(5);

public static void main(String[] args){
    MY_CIRCLE.radius = 10;  // final instances are mutable
}

 

Using Enums as Constants

Java 5 (1.5) and above supports enumerators and it can be used for defining constants. The following code fragment illustrates the use of Java enums for constant values,

// save in Color.java
public enum Color {
    BLACK, WHITE
}

// save in EnumTest.java
public class EnumTest {

    public static void test(Color c) {
        System.out.println(c);
    }
    
    public static void main(String[] args) {
        test(Color.BLACK);
    }
    
}