Task 3 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 — built-in methods

Lesson

What every enum can do

Every enum automatically provides useful methods. name() gives the constant's name as a String; ordinal() gives its position (starting at 0, in declaration order); values() returns an array of all the constants; and Type.valueOf("NAME") looks a constant up by name. Because values() is in declaration order, you can loop over every constant predictably.


Worked example

enum Color { RED, GREEN, BLUE }

System.out.println(Color.RED.name());      // RED
System.out.println(Color.GREEN.ordinal()); // 1
System.out.println(Color.values().length); // 3
Color c = Color.valueOf("BLUE");
System.out.println(c);                      // BLUE

for (Color col : Color.values()) {
    System.out.println(col);                // RED, then GREEN, then BLUE
}

▶ Try it: run this — inspect names, positions, and loop over all constants.



ordinal() returns...


values() returns...


Type exactly what this program prints.

enum Size { S, M, L }
public class Main { public static void main(String[] a){
    System.out.println(Size.M.ordinal());
    System.out.println(Size.values().length);
    System.out.println(Size.valueOf("L"));
}}

Color.valueOf("RED") gives...


True or false?