Skip to main content

How to convert Enum Contants into String: Inbuilt methods of Enum in java

 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

5. compareTo(E o)

  • Description: This method compares the ordinal values of two enum constants. It returns a negative integer, zero, or a positive integer depending on whether the calling enum constant's ordinal is less than, equal to, or greater than the ordinal of the specified enum constant.
  • Syntax: public int compareTo(E o)
  • Example:
enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

public class EnumMethodsExample {
    public static void main(String[] args) {
        Day today = Day.MONDAY;
        Day tomorrow = Day.TUESDAY;

        // Compare the ordinal values
        System.out.println(today.compareTo(tomorrow));  // Output: -1
    }
}
Output:
-1

6. getDeclaringClass()

  • Description: This method returns the Class object that represents the enum type.
  • Syntax: public Class<E> getDeclaringClass()
  • 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("Declaring class of the enum constant: " + today.getDeclaringClass());
    }
}
Output:
Declaring class of the enum constant: class Day

7. toString()

  • Description: This method returns the name of the enum constant as a string (same as name()). You can override this method to provide a custom string representation for your enum constants.
  • Syntax: public String toString()
  • Example:
enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
    
    @Override
    public String toString() {
        return "Day: " + name();
    }
}

public class EnumMethodsExample {
    public static void main(String[] args) {
        Day today = Day.MONDAY;
        System.out.println(today.toString());  // Custom toString method
    }
}
Output:
Day: MONDAY

Summary of Inbuilt Methods of Enum Class:

  1. values() – Returns an array of all enum constants.
  2. valueOf(String name) – Returns the enum constant matching the given name.
  3. ordinal() – Returns the ordinal value (position) of the constant.
  4. name() – Returns the name of the enum constant.
  5. compareTo(E o) – Compares ordinal values of two enum constants.
  6. getDeclaringClass() – Returns the Class object for the enum type.
  7. toString() – Returns a string representation of the enum constant.

These methods are available for all enum types and can be used to make your enum-based code more efficient and flexible.

Let me know if you need any more details!










Comments

Popular posts from this blog

equals method of object class in java

  In Java, the equals method is a fundamental method inherited by all classes from the Object class.           Here’s an explanation of the equals method: Purpose: The equals method is used to compare two objects to determine if they are logically equivalent. By default, the implementation in the Object class checks if the two object references point to the same memory location (i.e., if they are the same instance). Signature : public boolean equals(Object obj) Explanation: Method Override: Classes can override the equals method to provide their own definition of object equality based on their specific needs. When overriding, the method should adhere to certain principles to ensure consistency and correctness of equality comparisons. Default Behavior (from Object class): The default implementation in the Object class checks if the two object references ( this and obj ) refer to the exact same object in memory using the == operator: public boo...

What is static keyword in java

 Static variable: If we want to share the value of any field or variable inside all the instances of class then we should declare that variable as static. In above diagram we see that e1 and e2 are two objects of class Employee. they share the static variable companyName.  Static variables are also called as Class Variables because its copy gets shared between all the objects of same class.   Static variable gets space in method area at the time of class loading.   We can access static variables using object reference but it is designed to access using class name and dot operator.   Example:   Employee employee=new Employee(); object creation  System.out.println(“Company name:”+Employee.CompanyName): ok System.out.println(“Company name:”+employee.CompanyName): Ok  staticmethod

What is real use of interface: mostly asked interview question

Actually in real project development interfaces are use to write business logic code . Also Interfaces in java are powerful tools that allow you to define a contract for what a class can do, without specifying how it does it. it means we can give method declaration in interface and what that method does actually that responsibility is given to the class which is going to implement that class. They are used for several real-world purposes like enabling polymorphism , creating loosely coupled systems , and defining common behaviors across different classes . Real-World Use of Interfaces Let's look at some practical scenarios where interfaces are commonly used: 1. Multiple Inheritance (via Interfaces):  Java doesn't support multiple inheritance with classes, but it allows multiple inheritance with interfaces. This allows a class to implement multiple interfaces, enabling it to inherit behaviors from more than one source. 2. Polymorphism: Interfaces allow you to treat different o...