Implementing toString() on Enums in Java

06 May 2023 Balmiki Mandal 0 Core Java

Implementing toString() on enums in Java

Enums are great for preventing programming errors, since they allow us to work with a pre-defined set of constants. However, when working with enums we often also need to convert them to strings. In Java, there is a built-in method called toString() which can be used to do this. In this article, we’ll take a look at how to implement the toString() method on enums in Java.

The toString() Method

The toString() method is a method that is defined in class Object and is present in all classes (and, by extension, all enums) in Java. This method is used to convert an enum to a String representation. It can also be overridden, meaning you can write your own implementation of the method to handle specific cases.

Implementing toString() on Enums

The toString() method on enums can be implemented in the same way as it is done with any other class: by overriding the method in the enum itself. To do this, simply add the toString() method to the enum with your custom implementation. For example:

public enum Color {
  RED,
  GREEN,
  BLUE;
  
  @Override
  public String toString() {
    switch (this) {
      case RED:
        return "Red";
      case GREEN:
        return "Green";
      case BLUE:
        return "Blue";
      default:
        throw new IllegalArgumentException();
    }
  }
}

In the above example, we are overriding the toString() method so that it returns the string representation of the enum. This means that calling toString() on a Color enum will return a string representation of the color. This is useful when you need to print out the enum value or store it as a string.

Final Thoughts

Enums in Java are a great way to prevent programming errors, but sometimes we need to be able to convert them to string representations. Fortunately, this is easy to do with the built-in toString() method. By overriding this method in the enum itself, you can write your own implementation of the toString() method to provide an exact string representation of the enum value.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.