Sobes.tech
Senior

What is the name() method in enum?

sobes.tech AI

Answer from AI

The name() method in Java enum returns the exact name of the enum constant as a string, as it is declared in the code. This name is immutable and matches the enum constant's identifier.

Example:

enum Color {
    RED, GREEN, BLUE;
}

Color c = Color.RED;
System.out.println(c.name()); // Outputs "RED"

The difference from toString() is that name() always returns the original name of the constant, whereas toString() can be overridden for more convenient display.

What is the name() method in enum? — Java - sobes.tech