Question
In Java, enum values are compiled into class instances with private constructors and a fixed set of public static constants. When comparing two values from the same enum, I have usually written code like this:
public void useEnums(SomeEnum a) {
if (a.equals(SomeEnum.SOME_ENUM_VALUE)) {
// ...
}
}
However, I also found code that compares enum values using == instead:
public void useEnums2(SomeEnum a) {
if (a == SomeEnum.SOME_ENUM_VALUE) {
// ...
}
}
Which form should be used when comparing Java enum constants: == or .equals()?
Short Answer
By the end of this page, you will understand why Java enums are usually compared with ==, when .equals() also works, and why == is generally the safer and clearer choice. You will also see how enum comparison behaves with null, how it is used in real codebases, and what mistakes beginners commonly make.
Concept
In Java, an enum defines a fixed set of named constants. Each enum constant is a single shared instance of that enum type.
For example:
enum Status {
PENDING,
APPROVED,
REJECTED
}
Here, Status.PENDING is not just a value like a number or a string. It is a unique object instance created by the Java runtime. There is exactly one instance for each enum constant.
That is why == works so well with enums:
==checks whether two references point to the exact same object- enum constants are guaranteed to be unique singletons
- so identity comparison is the correct comparison
.equals() also returns the same result for enum constants, because enum equality is based on identity too. However, == is preferred because:
- it is simpler and clearer
- it directly expresses identity comparison
- it avoids
NullPointerExceptionin cases likea.equals(...)whenaisnull
This matters in real programming because enums are often used for:
Mental Model
Think of enum constants like official badges issued by a company.
- There is only one real badge for
MANAGER - There is only one real badge for
EMPLOYEE - If two people hold the exact same badge object, you can check that with
==
You do not need to inspect the badge contents with .equals() because the system guarantees there is only one official instance of each badge.
So with enums, == is like asking:
Is this the exact official enum constant?
That is exactly what you usually want.
Syntax and Examples
Basic syntax
Use == to compare enum constants:
enum Direction {
NORTH, SOUTH, EAST, WEST
}
public class Main {
public static void main(String[] args) {
Direction d = Direction.NORTH;
if (d == Direction.NORTH) {
System.out.println("Going north");
}
}
}
This works because Direction.NORTH is a single unique instance.
.equals() also works, but is not preferred
if (d.equals(Direction.NORTH)) {
System.out.println("Going north");
}
This is usually unnecessary. It is also less safe if d might be null.
Null-safe comparison
Direction d ;
(d == Direction.NORTH) {
System.out.println();
} {
System.out.println();
}
Step by Step Execution
Consider this example:
enum Light {
RED, GREEN, YELLOW
}
public class Demo {
public static void main(String[] args) {
Light current = Light.GREEN;
if (current == Light.GREEN) {
System.out.println("Go");
}
}
}
Step by step:
Lightis declared with three enum constants:RED,GREEN, andYELLOW.- Java creates one unique instance for each constant.
Light current = Light.GREEN;stores a reference to theGREENinstance.if (current == Light.GREEN)compares two references:current- the enum constant
Light.GREEN
- Both references point to the exact same enum instance.
- The condition evaluates to .
Real World Use Cases
Enums are commonly used wherever a program needs a small fixed set of valid options.
Application state
if (orderStatus == OrderStatus.SHIPPED) {
sendTrackingEmail();
}
User roles
if (userRole == Role.ADMIN) {
showAdminPanel();
}
Feature modes and configuration
if (environment == Environment.PRODUCTION) {
enableCaching();
}
API or workflow status handling
if (responseStatus == ApiStatus.ERROR) {
logFailure();
}
State machines
if (trafficLight == Light.RED) {
stopCars();
}
In all of these cases, == is the most natural comparison because you are checking whether a value is one specific enum constant.
Real Codebase Usage
In real Java projects, developers almost always compare enums with ==.
Common pattern: guard clauses
public void process(Status status) {
if (status == Status.DISABLED) {
return;
}
// continue processing
}
This is concise and null-safe.
Common pattern: validation and branching
public void handleRole(Role role) {
if (role == Role.ADMIN) {
grantAllPermissions();
} else if (role == Role.EDITOR) {
grantEditorPermissions();
}
}
Common pattern: switch with enums
When there are many enum cases, developers often use switch instead of repeated if checks:
switch (status) {
case PENDING:
System.out.println("Waiting");
break;
case PAID:
System.out.println("Completed");
;
FAILED:
System.out.println();
;
}
Common Mistakes
Mistake 1: Calling .equals() on a possibly null enum
Broken code:
Status status = null;
if (status.equals(Status.ACTIVE)) {
System.out.println("Active");
}
Problem:
- This throws
NullPointerException
Better:
if (status == Status.ACTIVE) {
System.out.println("Active");
}
Mistake 2: Treating enums like strings
Broken thinking:
- Strings are often compared with
.equals() - so beginners assume enums should be compared the same way
But enums are different:
- strings may have different object instances with the same text
- enum constants are unique single instances
Correct:
if (level == Level.HIGH) {
alert();
}
Mistake 3: Comparing enum names as text unnecessarily
Broken code:
Comparisons
| Comparison style | Works for enums? | Null-safe when variable may be null? | Recommended? | Notes |
|---|---|---|---|---|
a == SomeEnum.VALUE | Yes | Yes | Yes | Best choice for enum constants |
a.equals(SomeEnum.VALUE) | Yes | No | Usually no | Throws if a is null |
SomeEnum.VALUE.equals(a) | Yes | Yes | Sometimes acceptable | Null-safe, but less idiomatic than == |
a.name().equals("VALUE") |
Cheat Sheet
// Preferred enum comparison
if (status == Status.ACTIVE) {
// ...
}
// Works, but not preferred
if (status.equals(Status.ACTIVE)) {
// ...
}
Rules
- Use
==to compare enum constants ==is safe even if the enum variable isnull.equals()works, but can throwNullPointerException- Do not compare enums using
name()unless you specifically need text - Do not use
ordinal()for business logic
Null behavior
Status status = null;
status == Status.ACTIVE // false
status.equals(Status.ACTIVE) // NullPointerException
Best practice
if (role == Role.ADMIN) {
allowAccess();
}
Remember
FAQ
Should I always use == for Java enums?
Yes, in normal enum-to-enum comparisons, == is the standard and recommended approach.
Does .equals() work for enums in Java?
Yes, it works when the enum reference is not null, but it is usually unnecessary.
Why is == safe for enums but not for strings?
Enum constants are unique singleton instances. Strings are regular objects, so two different string objects can contain the same text.
Can == throw a NullPointerException with enums?
No. If the enum variable is null, the comparison simply evaluates to false.
Is SomeEnum.VALUE.equals(a) better than a.equals(SomeEnum.VALUE)?
It is safer because it avoids NullPointerException when a is null, but a == SomeEnum.VALUE is still clearer and more idiomatic.
Mini Project
Description
Build a small Java program that processes an order status using an enum. This project demonstrates the correct way to compare enum constants with ==, how to handle null safely, and how enum-based branching appears in practical code.
Goal
Create a program that reads an order status value and prints the correct action for each status using enum comparison.
Requirements
- Create an
OrderStatusenum with at leastPENDING,PAID,SHIPPED, andCANCELLED. - Write a method that accepts an
OrderStatusvalue and prints a message based on the status. - Use
==for enum comparisons. - Handle a
nullstatus safely. - Include a
mainmethod that tests multiple status values.
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.