Jack Ng

Essay

Learning Java, Part 12: Enums, Autoboxing, Static Import and Annotations

Study notes on enumerations as classes with values, valueOf, constructors, fields and methods, the type wrappers, autoboxing and unboxing and their traps, static import, and built-in annotations. Written entirely by an AI model.

Four features added in Java 5 that the rest of the language now relies on. Enums and the wrapper classes matter most: generics (Part 13) only work because of the wrappers.

Enumerations

An enum is a type with a fixed set of named values. Use one wherever you would otherwise use magic numbers or strings for a small closed set:

enum Size { SMALL, MEDIUM, LARGE }

public class Sizes {
    public static void main(String[] args) {
        Size s = Size.MEDIUM;
        System.out.println(s);

        switch (s) {                        // no "Size." prefix in case labels
            case SMALL -> System.out.println("250 ml");
            case MEDIUM -> System.out.println("350 ml");
            case LARGE -> System.out.println("450 ml");
        }

        for (Size each : Size.values()) {
            System.out.print(each + "=" + each.ordinal() + " ");
        }
        System.out.println();
        System.out.println(Size.valueOf("LARGE") == Size.LARGE);
        System.out.println(Size.SMALL.compareTo(Size.LARGE) < 0);
    }
}
MEDIUM
350 ml
SMALL=0 MEDIUM=1 LARGE=2
true
true
  • values() returns every constant, in declaration order. valueOf(String) finds one by name and throws IllegalArgumentException for an unknown name.
  • Each constant is a single object, so comparing with == is correct and safe.
  • ordinal() gives the position, starting at 0. Don’t store it; reordering the constants changes it.
  • The compiler knows every value, so a switch can cover them all. With the arrow form and no default, a switch expression that misses a constant does not compile.

Enums are classes

Unlike C, a Java enum is a full class. Its constants are its only instances, created when the class loads. It can have fields, a constructor and methods:

enum Coin {
    FIVE(5), TEN(10), TWENTY(20), FIFTY(50);

    private final int cents;            // each constant has its own value
    Coin(int cents) { this.cents = cents; }
    int cents() { return cents; }

    static int total(Coin... coins) {
        int sum = 0;
        for (Coin c : coins) sum += c.cents();
        return sum;
    }
}

public class Purse {
    public static void main(String[] args) {
        System.out.println(Coin.TWENTY.cents());
        System.out.println(Coin.total(Coin.FIFTY, Coin.TEN, Coin.TEN));
    }
}
20
70

Two restrictions: an enum cannot extend another class (it implicitly extends java.lang.Enum), and you cannot create instances with new, because the constructor is effectively private. An enum can implement interfaces, and each constant can even override a method in its own body.

The book’s traffic-light exercise uses an enum for the light’s state, with a thread changing it.

Type wrappers

Each primitive has a wrapper class that holds one value as an object:

Primitive Wrapper
int Integer
long Long
double Double
char Character
boolean Boolean
byte, short, float Byte, Short, Float

Wrappers are needed wherever Java expects an object, above all in collections: ArrayList<int> is illegal, ArrayList<Integer> is fine. They also hold useful static methods: Integer.parseInt, Integer.MAX_VALUE, Character.isDigit, Double.compare.

Autoboxing and unboxing

Java converts between a primitive and its wrapper automatically. Wrapping is autoboxing; extracting is unboxing:

import java.util.ArrayList;
import java.util.List;

public class Boxing {
    public static void main(String[] args) {
        Integer boxed = 42;            // autobox: Integer.valueOf(42)
        int plain = boxed + 1;         // unbox, add, keep as int
        List<Integer> marks = new ArrayList<>();
        marks.add(73);                 // autobox
        int first = marks.get(0);      // unbox
        System.out.println(plain + " " + first);
        System.out.println(Character.isLetter('x') + " " + Integer.toBinaryString(5));
    }
}
43 73
true 101

Two traps

Boxing happens so quietly that it causes bugs that are easy to miss:

public class BoxTraps {
    public static void main(String[] args) {
        Integer a = 127, b = 127;
        Integer c = 128, d = 128;
        System.out.println(a == b);        // small values are cached
        System.out.println(c == d);        // different objects
        System.out.println(c.equals(d));

        Integer missing = null;
        try {
            int x = missing;               // unboxing null
        } catch (NullPointerException e) {
            System.out.println("NullPointerException");
        }
    }
}
true
false
true
NullPointerException
  1. == on wrappers compares references. Java caches Integer objects from −128 to 127, so == happens to work for small numbers and then fails at 128. Compare wrappers with equals, or unbox first.
  2. Unboxing null throws NullPointerException. This often happens with a Map<String, Integer> whose get returns null for a missing key.

Boxing also costs time and memory. In a tight numeric loop, use primitives.

Static import

import static brings static members into scope, so they can be used without the class name:

import static java.lang.Math.*;

public class Hyp {
    public static void main(String[] args) {
        System.out.println(sqrt(pow(3, 2) + pow(4, 2)));
        System.out.println(max(PI, E));
    }
}
5.0
3.141592653589793

Use it sparingly. In a large file, a bare max gives the reader no clue where it came from. Its main everyday use is in tests: import static org.junit.jupiter.api.Assertions.*;.

Annotations

An annotation is metadata attached to code, written with @. It does not change what the code does by itself; the compiler, tools or frameworks read it. Built-in ones:

Annotation Meaning
@Override this method must override a superclass or interface method; error otherwise
@Deprecated don’t use this; the compiler warns callers
@SuppressWarnings("unchecked") silence a named warning for this element
@FunctionalInterface this interface must have exactly one abstract method (Part 14)
@SafeVarargs promise that a generic varargs method is safe
public class Notes {
    @Deprecated
    static int oldTotal(int a, int b) { return a + b; }

    @Override
    public String toString() { return "Notes"; }

    public static void main(String[] args) {
        System.out.println(new Notes() + " " + oldTotal(1, 2));
    }
}
Notes 3

You can declare your own with @interface, and frameworks you will meet later rely heavily on annotations: @Test in JUnit (Part 16), and routing annotations in web frameworks. Annotations with runtime retention can be read while the program runs, through reflection.

Exam-style checks

  • Give two advantages of an enum over a set of int constants.
  • Write an enum with a constructor and a field, and explain why its constructor cannot be public.
  • What is autoboxing? Give an example where it causes a NullPointerException.
  • Why can Integer a = 127, b = 127; a == b be true while the same code with 128 is false?
  • What does @Override do, and what bug does it catch?

Where to practise

Write an enum Planet with mass and radius fields and a method for surface gravity, then loop over values() to print a table. Write the traffic-light simulation from Schildt’s Chapter 12 with an enum for the colour. Then put the boxing traps into jshell and try other values until the caching boundary makes sense.