DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Trending

  • Scaling Mobile App Performance: How We Cut Screen Load Time From 8s to 2s
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  • Measuring the Impact of AI on Software Engineering Productivity
  1. DZone
  2. Coding
  3. Java
  4. How to Define Constants in Java

How to Define Constants in Java

Learn more about defining constants in Java!

By 
An Eng user avatar
An Eng
·
Updated Nov. 18, 19 · Tutorial
Likes (15)
Comment
Save
Tweet
Share
100.0K Views

Join the DZone community and get the full member experience.

Join For Free

There seems to be a lot of confusion around the topic of constants in Java. Some people make use of integers or Strings to define constants, while others make use of enums.

I’ve also come across constants defined in their own interface — where classes that make use of the constants have to implement the interface. This strategy is often referred to as the interface constant design pattern.

In this article, we’ll have a look at the two most common strategies for storing constants in Java: integers and enums.

First and foremost, whenever you decide to use constants, you should be pretty certain that the constants won’t change over time so you can avoid recompiling.

In this article, we’ll work with a very common candidate for constants – weekdays!

  • Tip: Check out our review of the top 10 best Java courses on Udemy!

Let’s assume that we have a class representing an order in an online store, where we want to keep track of which day of the week the order occurred.

Our class looks like this:

public class Order {
    private [datatype] weekDay;

    public [datatype] getWeekDay() {
        return weekDay;
    }

    public void setWeekDay([datatype] weekDay) {
        this.weekDay = weekDay;
    }
}


Note that the class won’t compile for the moment – [datatype] is simply a placeholder for the type of constant we’ll use.

Defining Constants With Integers

One of the most common ways to define constants in Java is through integers, where the integer variables are static.

public static int MONDAY = 0;
public static int TUESDAY = 1;
public static int WEDNESDAY = 2;
public static int THURSDAY = 3;
public static int FRIDAY = 4;
public static int SATURDAY = 5;
public static int SUNDAY = 6;


The first question to ask when defining integer constants is where to place them. Do we place them directly in the Order class? Or do we give them their own class?

Since days are pretty general, and not necessarily just connected to objects of type Order, we’ll define them in their own class WeekDay.

public class WeekDay {

    private WeekDay(){}

    public static int MONDAY = 0;
    public static int TUESDAY = 1;
    public static int WEDNESDAY = 2;
    public static int THURSDAY = 3;
    public static int FRIDAY = 4;
    public static int SATURDAY = 5;
    public static int SUNDAY = 6;
}


You probably noticed the private constructor – this is to avoid clients from instantiating the class. The class holds only static variables, which are not tied to an object, so there is no need to instantiate the class.

Now, whenever we need to set a particular day to an order, we do it like this:

Order order = new Order();
order.setWeekDay(WeekDay.MONDAY);


And when we want to check whether an order occurred on a Friday, we can simply call write:

 if(order.getWeekDay() == WeekDay.FRIDAY) 

So far, so good. There surely can’t be any problems with this design?

Well, let’s assume that you’re coming back to this code a year later – and you have to check whether an order occurred on a Monday.

Oh, and of course – you have completely forgotten about the WeekDay class... 
In this scenario, you might try something like this:

 if(order.getWeekDay() == 1) 

At that moment, having completely forgotten about the WeekDay class, this code makes perfect sense. Monday is the first day of the week, so weekday should be 1, right?

But no, it isn’t, because the static int variable Monday is defined as 0 in our WeekDay class!

This is a great example of why you should consider avoiding the use of integer constants. They are error-prone, confusing, and hard to debug.

Defining Constants With Enums

One other alternative to defining constants in Java is by using enums.

When using enums, our constants class will look something like this:

public enum WeekDay {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}


Notice the absence of the private constructor — there’s no need for the programmer (you!) to enforce that the class is non-instantiable since enums are non-instantiable by default!

The syntax for setting a WeekDay to an order is exactly the same as with integer constants:

 order.setWeekDay(WeekDay.MONDAY);

There is also no difference in how we can whether the order was processed on a Friday:

 if(order.getWeekDay() == WeekDay.FRIDAY) 

However, the key difference is that this is the only way you can set and compare values for the weekday variable in the Order class.

Both order.setWeekDay(1); and if(order.getWeekDay() == 1) will make the compiler throw an error since you are trying to use variables of type integerwhen they should be of type WeekDay!

Think back to the scenario when you had completely forgotten about the WeekDay class.
With enums, this is no longer an issue. If you try to use integers instead of members of the WeekDay enum, the compiler will simply throw an error, telling you that you need to use the WeekDay enum.

Said in other words, the only thing that will work for you to check whether an order occurred on a Friday is:

 if(order.getWeekDay == WeekDay.FRIDAY) 

It doesn’t get any clearer than this!

You’re no longer forced to remember the constants class, and if any clients were to use your code, they don’t have to wonder whether Monday is actually represented by a 0 or a 1.

I hope this example demonstrated to you why you should consider using enums over integers when defining constants.

Enums will make your code less error-prone, easier to read, and more maintainable!

A quick tip: If you wish to expand your Java skill-set and become an advanced Java developer, I highly recommend you to get yourself a copy of the best-selling Effective Java, by Joshua Bloch!

Java (programming language)

Published at DZone with permission of An Eng. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!