Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

enum
string
java

Enum to String in Java

Educative Answers Team

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());

RELATED TAGS

enum
string
java
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring