I am going through some code uses the name
method of a Java Enum.
Can anyone please explain to me how and where to use the name()
method of Enum in java.
Given:
enum Direction {
NORTH("north"), SOUTH("south"), EAST("east"), WEST("west");
private final String printableValue;
Direction(String printableValue) {
this.printableValue = printableValue;
}
@Override
public String toString() {
return printableValue;
}
}
then this code:
Direction travelDirection = Direction.NORTH;
System.out.println("I am going " + travelDirection);
will print
I am going north
but this code:
Direction travelDirection = Direction.NORTH;
System.out.println("I am going " + travelDirection.name());
will print
I am going NORTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With