Home » Core Java » Java Constant Example

About Venkat-Raman Nagarajan

Venkat-Raman Nagarajan
Venkat works for a major IT firm in India and has more than a decade of experience working and managing Java projects for a banking client.

Java Constant Example

A Java constant is used to represent a value that cannot be changed after assignment. Constants make a program more readable and can take the modifiers static and final. Let us look into some examples for Java constants and their best practices in this article.

1. Java constant examples and best practices

1.1 Usage of final

The final modifier indicates that the value cannot be modified after assignment. Primitive data types (boolean, byte, char, int, short, long, float, double) can be made immutable using final modifier. Let us consider a simple example where a constant variable’s usage is restricted to only a class. In such case, we can declare the variable with final modifier and access as private.

Usage of final
/**
 * This class provides samples for usage of constants
 * 
 */
public class WageCalculator {
    // constant used only within this class
    private final double WAGE_PER_HOUR = 40.00;
    public static final double MIN_WAGE_PER_HOUR = 10.00;
    
    /*
    method to calculate wages based on number of days worked.
    */
    public void wageCalculation(int numWorkingDays){
        
        System.out.println("Wage for this month :"+ 
                numWorkingDays * WAGE_PER_HOUR);
        
        /* Note that the below statement would show an error as we are 
         updating a variable declared as final */
        //WAGE_PER_HOUR=50.00;
    }
}

In the above example, variable WAGE_PER_HOUR is declared as final and access as private. You will notice an error when you try to reassign the value (Line 20).

Note that the behavior would be different for objects declared as final. Assigning final indicates that the reference (pointer) to an object cannot change. But if the referenced object is mutable, then the contents of the object can still be modified.

1.2 Usage of static

We use the modifiers static and final if the scope of the constant variable is beyond this class. The static modifier allows a variable to be used without creating an instance of this class. In the above example, MIN_WAGE_PER_HOUR could be referenced in other classes as WageCalculator.MIN_WAGE_PER_HOUR. We could use static import to make the code more readable by removing the boilerplate of the repetition of class names. But do note that overuse of static import feature can make code un-maintainable by polluting the namespace with all the static members that we import. Refer java doc for further details.

1.3 Declaring constants

The usual naming convention for constant variables is to use upper case letters with underscores (example – MIN_WAGE_PER_HOUR as shown in the above example).

Constants are declared in a class as public or protected when they are valid only to a particular class or its sub-classes. It is not advisable to have all the constants defined in a single constant interface (such an interface does not contain methods. It consists of solely static final fields, each exporting a constant. Classes would then implement this interface to avoid the need to qualify constant names). Joshua Bloch terms this as Constant interface pattern in Effective Java Edition 3 (Item#22). The recommended approaches are:

  1. If the constants are strongly tied to an existing class or interface – add them to the class or interface
  2. If the constants are best viewed as members of an enumerated type – export them with an enum type
  3. Export constants with a non-instantiable utility class as shown in the below example.
Utility class for constants
/**
 * Class has constants needed for Accounts module
 */
public class AccountsConstants {
    // private constructor to avoid instantiation
    private AccountsConstants(){}
    
    // constants for product codes
    public static final String SAVING_ACCT_PROD_CODE = "010";
    public static final String CURRENT_ACCT_PROD_CODE = "011";
    public static final String HOMELOAN_ACCT_PROD_CODE = "012";
    public static final String DEPOSIT_ACCT_PROD_CODE = "013";
}

1.4 Usage of enums

An enum type is a special data type that allows a variable to be a set of predefined constants. The variable must be equal to one of the variables that have been predefined for it. Common examples could be days of the week or compass directions. Refer java docs for more details on enums.

Example for enum
/**
 * Class to explain enums
 */
public class EnumExample {
    Day day;
    
    public EnumExample(Day day){
        this.day = day;
    }
    
    public void dayDetail(){
        switch(day){
            case SUNDAY: case SATURDAY:
                System.out.println("Weekend");
                break;
            default:
                System.out.println("Weekday");
                break;
        }
    }
    
    public static void main(String args[]){
        EnumExample ex = new EnumExample(Day.SUNDAY);
        ex.dayDetail();
        ex = new EnumExample(Day.FRIDAY);
        ex.dayDetail();
        
    }
}

// enum to indicate Day
enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
} 

2. Download the Source Code

In this article we discussed about Java constants with some examples.
Download
You can download the full source code of this example here: Java Constant Example


(+1 rating, 1 votes)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Bill Fly Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Bill Fly
Guest
Bill Fly

Link to code is wrong.