Enums – Smart Constants in Java

You've learned about classes and objects — great! Now let’s explore a special kind of class that helps you represent fixed sets of related values: enums. Enums, short for enumerations, are like a list of constants that belong together. They let you define a type with a fixed set of possible values, making your code cleaner and safer.

Why Enums?

Say you're building a program that tracks days of the week. You could use Strings:

days of week using strings

But what if someone types "Mondya"? No compiler error — just a sneaky bug. That’s why we have enums. Enums let you define a closed set of constant values. The compiler enforces valid values, making your code cleaner and safer.

Declaring an Enum

Here’s how you define one:

days of week using enum

And use it like this:

using days of week enum

You can’t assign today = "Monday"; — the compiler won’t allow it. That’s safety right there.

Using Enums in Switch Statements

Enums work great with switch:

switch statement with enum

No need to compare strings — it’s cleaner and faster.

Enums with Fields and Methods

Enums can be more than just labels. They can have fields, constructors, and methods:

enum with fields and methods

Usage:

using enum with fields and methods

This turns enums into powerful, structured constants.

Enum Recap

Practice!

Create an enum called TrafficLight with values RED, YELLOW, GREEN.
Add a method to describe each one.
Use a switch statement to print behavior based on the value.

What’s Next

Now that you’ve learned enums, you’re ready to work with groups of objects and values using Java Collections — coming up next! Let’s explore arrays, lists, maps, and sets, and learn how to store and organize real data.