Java enum FAQ: Can you share a Java enum toString
example?
I haven’t tried this before, but I was just working on several Java enum examples (Java enum examples tutorial, Java enum switch example), and I thought I’d take a look at the Java enum toString
behavior.
To that end I wrote the following Java enum “toString” example class:
/** * A Java enum toString example. * @author alvin alexander, alvinalexander.com */ public class JavaEnumToStringExample { public static void main(String[] args) { // loop through the enum values, calling the // enum toString method for each enum constant for (Day d: Day.values()) { System.out.println(d); } } } enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
This enum toString example class iterates through the Day
enum with the enum for
loop shown here:
// this enum for loop iterates through each constant in the // Day enum, implicitly calling the toString method for each enum // constant that is passed into the println method: for (Day d: Day.values()) { System.out.println(d); }
Java enum toString program output
The output from the enum toString
example looks like this:
SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY
Calling the enum toString method explicitly
In the enum for
loop code above, I mentioned that the toString
method is being called implicitly. If you prefer to call the enum toString
method explicitly, you can just change the print statement, as shown here:
for (Day d: Day.values()) { System.out.println(d.toString()); }
Summary
Again, nothing major here, I just wanted to explore the enum toString
behavior while I was in the neighborhood. If you have any questions, comments, or more complicated "enum toString" examples you'd like to share, feel free to leave a note in the comments section below.
Java enum toString example - What's Related
As I finish up my Java enum series, including this Java enum toString example, here's a collection of the Java enum tutorials I've put together during the last week. I hope you find them helpful: