In Java, the toString()
method is a member of the Object
class, which is the superclass of all objects in Java. The toString()
method returns a String
representation of an object.
In the case of an enum
type, the toString()
method returns the name of the enum
value as a String
.
Here's an example of how to use the toString()
method with an enum
in Java:
public enum Size { SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL"); private String abbreviation; private Size(String abbreviation) { this.abbreviation = abbreviation; } public String getAbbreviation() { return abbreviation; } public static void main(String[] args) { Size size = Size.LARGE; String toString = size.toString(); // toString is "LARGE" System.out.println(toString); } }
In this example, the Size
enum
has four constant values: SMALL
, MEDIUM
, LARGE
, and EXTRA_LARGE
. The toString()
method is called on the size
variable and returns the String
representation of the enum
value.
You can use the toString()
method to get the String
representation of an enum
value in Java. The toString()
method is useful for displaying the enum
value in a user-friendly way.