In Java, every enum type inherits several built-in methods from the java.lang.Enum
class, which is the base class for all enum types. These built-in methods provide functionality such as getting the name of an enum constant, comparing enum constants, and iterating over all constants.
Here are the inbuilt methods provided by the Enum
class:
1. values()
- Description: This method returns an array of all the constants of the enum type, in the order they were declared.
- Syntax:
public static T[] values()
- Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class EnumMethodsExample {
public static void main(String[] args) {
Day[] days = Day.values(); // Get all enum constants
// Loop through the array and print each day
for (Day day : days) {
System.out.println(day);
}
}
}
Output:
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
2. valueOf(String name)
- Description: This method returns the enum constant of the specified name. The name must exactly match the identifier used to declare the enum constant (case-sensitive).
- Syntax:
public static T valueOf(String name)
- Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class EnumMethodsExample {
public static void main(String[] args) {
Day today = Day.valueOf("MONDAY"); // Get enum constant by name
System.out.println("Today is: " + today);
}
}
Output:
Today is: MONDAY
If you provide an invalid name, a IllegalArgumentException
will be thrown:
Day invalidDay = Day.valueOf("FUNDAY"); // Throws IllegalArgumentException
3. ordinal()
- Description: This method returns the ordinal value (position) of the enum constant in its declaration. The first constant has an ordinal of 0, the second has an ordinal of 1, and so on.
- Syntax:
public int ordinal()
- Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class EnumMethodsExample {
public static void main(String[] args) {
Day today = Day.WEDNESDAY;
System.out.println("Ordinal of " + today + " is: " + today.ordinal());
}
}
Output:
Ordinal of WEDNESDAY is: 2
4. name()
- Description: This method returns the name of the enum constant exactly as declared in the enum type (case-sensitive).
- Syntax:
public String name()
- Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class EnumMethodsExample {
public static void main(String[] args) {
Day today = Day.MONDAY;
System.out.println("Name of the day: " + today.name());
}
}
Output:
Name of the day: MONDAY
Comments
Post a Comment