Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the name() method in Java enums [closed]

Tags:

java

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.

like image 671
Sharanabasu Angadi Avatar asked Dec 27 '22 20:12

Sharanabasu Angadi


1 Answers

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
like image 104
Simon Nickerson Avatar answered Jan 08 '23 04:01

Simon Nickerson