John White John White - 8 months ago 31
Java Question

Java: Can one get printf to show an enum's name?

I notice that println() does this, but I cannot get it to work in printf().

In the following snippet, the first two println's give RED and BLUE, then the printf crashes.

class Jim {
public enum Colours {BLUE, RED}
static Colours xx = Colours.RED;
public static void main(String[] args) {
Colours fred = Colours.BLUE;
System.out.printf("%d, %d\n", fred, xx);


%d format specifiers are not compatible with enum types unless used against the ordinal value. To invoke the enum's toString method (which uses the name field) you can use %s instead

System.out.printf("%s, %s%n", fred, xx);

Read: Enum