Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

11.1 Enums — a type with a fixed set of values

Lesson

Naming a fixed set of choices

An enum (enumeration) defines a type whose values are a fixed, named set of constants — perfect for things like days, directions, or states. Declare it with the enum keyword. Access a constant as Type.CONSTANT, and compare enum values with == (each constant is a single shared object).


Worked example

enum Day { MON, TUE, WED }

Day d = Day.MON;
System.out.println(d);              // MON
System.out.println(d == Day.MON);   // true
System.out.println(d == Day.TUE);   // false

Using an enum instead of loose int codes or Strings means the compiler checks that only real, valid values are used.


▶ Try it: run this — assign a constant and compare it with ==.



An enum defines...


You compare two enum values with...


Type exactly what this program prints.

enum Light { OFF, ON }
public class Main { public static void main(String[] a){
    Light x = Light.ON;
    System.out.println(x);
    System.out.println(x == Light.OFF);
}}

An advantage of an enum over an int code is...


True or false?