Enums in conditionals

Enums are a good fit into conditional expressions (if statements or switch blocks). The nice thing about enums is that they are constant values so you can compare them with the == operator which is more elegant than using equals() — and it avoids possible NullPointerExceptions. And by the way: if you look at the implementation of equals() of the Enum class you will see the following:

Example:

public enum Workday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
}


if(currentSchedule.getWorkday() == Workday.FRIDAY) {
System.out.println("Hurray! Tomorrow is weekend!");
}
-----------------------------------------------------



Comments