Course contentsShow
← Java
Lesson 586 of 2,87014. EnumerationsFree lesson

Type Safety: Enums vs Constants

Comparing enums to int or String constants and understanding compile-time type safety benefits.

Type Safety: Enums vs Constants

What you'll learn: You'll understand why enums provide compile-time safety that simple integer or String constants cannot match.

Before enums existed, developers often used constants to represent fixed sets of values:

public class Status {
    public static final int PENDING = 0;
    public static final int APPROVED = 1;
    public static final int REJECTED = 2;
}

The problem? The compiler treats these as ordinary integers. Nothing stops you from writing nonsense:

int status = 999;  // compiles fine, but meaningless
status = Status.PENDING + Status.APPROVED;  // nonsense math, still compiles

String constants have similar issues:

String status = "PENDIGN";  // typo, no compiler error

How Enums Provide Type Safety

Enums create a distinct type that the compiler enforces:

public enum Status {
    PENDING, APPROVED, REJECTED
}

Status status = Status.PENDING;  // correct
status = 999;  // COMPILER ERROR: incompatible types
status = Status.APPROVED + Status.REJECTED;  // COMPILER ERROR: operator + cannot be applied to Status

The compiler knows what values are legal. You cannot assign random integers, perform meaningless operations, or make typos that compile. Think of it like ordering from a menu versus shouting random words—the menu constrains your choices to valid options.

The Difference in switch Statements

With constants, the compiler can't verify completeness:

switch (statusInt) {
    case Status.PENDING: break;
    // forgot APPROVED and REJECTED - no warning
}

With enums, modern IDEs warn about missing cases, and you can't accidentally use the wrong constant type.

Key Takeaway: Enums provide compile-time type safety by creating distinct types that prevent invalid values, meaningless operations, and typos—problems that int and String constants cannot catch.