Home › Learn › Java › Interfaces, generics, and streams

Enums

Lesson 32 of 40. A type with a fixed set of named values.

enum Status { AVAILABLE, ON_LOAN, LOST } declares a type whose only values are those three constants. A variable of type Status can hold nothing else, which makes states and options safe to pass around: no misspelled strings, and a switch over an enum can be checked for completeness. Status.valueOf("LOST") parses text, s.name() gives the text back, Status.values() lists them all, and s.ordinal() is the position.

Enums are classes: they can have fields set through a constructor, and methods. enum Size { SMALL(8), LARGE(16); final int ounces; Size(int ounces) { this.ounces = ounces; } } gives each constant its own data.

The library project tracks each book's state with the Status enum from this lesson.

enum Day { MON, TUE, WED, THU, FRI, SAT, SUN;
    boolean isWeekend() {
        return this == SAT || this == SUN;
    }
}

System.out.println(Day.SAT.isWeekend() + " " + Day.valueOf("MON"));   // true MON

Your task

Write enum Status { AVAILABLE, ON_LOAN, LOST } with a method boolean canBeBorrowed() that is true only for AVAILABLE, and enum Size with the constants SMALL, MEDIUM, and LARGE holding 8, 12, and 16 ounces in a field ounces set by the constructor, plus a method Size next() returning the next larger size (LARGE stays LARGE).

Part of the final project. Status is the state of a book: available, on loan, or lost. It is saved in this browser and loaded into Project: the library when you get there.

Hint 1

boolean canBeBorrowed() { return this == AVAILABLE; }

Hint 2

final int ounces; Size(int ounces) { this.ounces = ounces; } Size next() { return this == LARGE ? LARGE : values()[ordinal() + 1]; }

Show the solution
public class Main {
    public static void main(String[] args) {
        System.out.println(Status.AVAILABLE.canBeBorrowed() + " " + Size.SMALL.next());
    }
}

enum Status {
    AVAILABLE, ON_LOAN, LOST;

    boolean canBeBorrowed() {
        return this == AVAILABLE;
    }
}

enum Size {
    SMALL(8), MEDIUM(12), LARGE(16);

    final int ounces;

    Size(int ounces) {
        this.ounces = ounces;
    }

    Size next() {
        return this == LARGE ? LARGE : values()[ordinal() + 1];
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.