Enum to String in Java

An enum in Java can be considered as an object that contains several constants. It is similar to final variables.

Sometimes, there occurs a need to convert an enum to a string. This can be solved using one of two methods:

  • name()
  • toString()

Suppose there is an enum that contains student names:

public enum Students {
  TOM, HARRY, SARA, PATRICK;
}

Enum to String using name()

System.out.println(Students.TOM.name());       
System.out.println(Students.HARRY.name());
System.out.println(Students.SARA.name());
System.out.println(Students.PATRICK.name());

Enum to String using toString()

System.out.println(Students.TOM.toString());       
System.out.println(Students.HARRY.toString());
System.out.println(Students.SARA.toString());
System.out.println(Students.PATRICK.toString());

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved