Java Enum valueOf()

The enum class is included in java.lang package. It is the universal foundation class for all enumeration types in the Java language. The valueOf method of the Java Enum class is used to retrieve. Enum constants are declared in Enum Types by giving a String or converting String to Enum constants.

The Enum class’s valueOf() function returns the enum constant of the specified enum type along with the specified name.

Java Enum valueOf() Syntax

public static > T valueOf(Class enumType,String name)

Parameters

T: The yielded constant is of the enum type.

enumType – The enum type’s Class object returns a constant.

name – It will return the name of the constant.

Value of the Return

The enum constant is returned along with the defined name by the valueOf() method.

Throws

The valueOf() function throws the following exception:

If the defined enum type is inconsistent with the specified name, or if the defined class object does not illustrate an enum type, an IllegalArgumentException is thrown. If the value of enumType or name is null, a NullPointerException is thrown.

enum Companies{  
  
IBM, Amazon, Google, Facebook, Twitter;  
  
}  
  
public class Enum_valueOfTechCompanies {  
  
public static void main(String[] args) {  
  
System.out.println("What is the name of the company:");  
  
for( Companies comp : Companies.values()){  
  
int i = part.ordinal()+1;  
  
System.out.println(i+" "+comp);  
  
        }  
  
      Companies comp = Companies.valueOf("IBM");  
  
System.out.println("\nAns: "+comp);  
  
       }  
}

Example: enum on programming languages

enum Languages{  
  
Python, Java, JavaScript, C, Kotlin;  
  
}  
  
public class Enum_valueOfProgrammingLanguage {  
  
public static void main(String[] args) {  
  
System.out.println("Choose your programming languages:");  
  
for( Languages planguage : Languages.values()) {  
  
System.out.println(Languages.valueOf(" "));  
  
        }  
  
    }  
  
}

}

As can be seen, Enum is an abstract class. Hence we cannot generate Enum objects.

Enum Class Methods

The Enum class has ten essential methods. The Object class overrides the majority of them. The Enum class declares these methods as final, preventing the programmer from changing any enum constants.

final String name()

This function returns the name of this enum constant, which is the same as the enum declaration.

The syntax is as follows :

public final String name()
public final String name()

// program  demonstrating the name() method
enum Cities
{
	London, New York, Manchester;
}

public class nameTest
{

	public static void main(String[] args)
	{
		Cities cityName = Cities.Manchester;
		System.out.print("enum's constant is: ");

		// method's name
		System.out.println(cityName .name());
	}
}

final int ordinal()

This method returns the index of this enumeration constant. final int ordinal():

The Syntax is as follows :

public final int ordinal()
// program  demonstrating the ordinal() method
enum Cities
{
	London, New York, Manchester;
}

public class ordinalTest
{
	// Driver method
	public static void main(String[] args)
	{
		Cities cOrdinal = Cities.London;
		System.out.print("ordinal of enum constant "+cOrdinal .name()+" : ");

		// ordinal method
		System.out.println(cOrdinal .ordinal());
	}
}

String toString()

String toString() returns a String object representing this enumeration constant. This method is identical to the name() method.

The syntax is as follows :

// program  demonstrating the toString() method
enum Cities
{
	London, New York, Manchester;
}

public class toStringTest
{
	// Driver method
	public static void main(String[] args)
	{
		Cities cString = Cities.GREEN;
		
		// fetch string representation of enum
		// using toString() method
		String strCities = Cities.toString();
		
		System.out.println(strCities);
	}
}

final boolean equals(Object obj)

final boolean equals(Object obj): If the supplied object is equal to this enum constant, this function returns true; otherwise, it returns false.

The syntax is as follows:

public final boolean equals(Object obj)
// program  demonstrating the equals() method
enum Cities
{
	London, Austin, Manchester;
}

public class equalsTest
{

	public static void main(String[] args)
	{
		Cities cOne = Cities.London ;
		Cities cTwo = Cities.Austin ;
		Cities cThree = Cities.Manchester ;
		
		// equality checking between enums
		// using equals() method
		
		boolean bOne = cOne.equals(cTwo);
		boolean bTwo = cOne.equals(cThree);
		boolean bThree = cTwo.equals(null);
		
		System.out.println("is cOne equal to cTwo : " + bOne);
		System.out.println("is cOne equal to cThree : " + bTwo);
		System.out.println("is cTwo equal to null : " + bThree);
	}
}

final int hashCode()

This method returns a hash code for this enum constant. This method returns a hash code for this enum constant. Actually, this function only comprises one statement: “return super.hashCode(),” which calls the hashCode() method of the Object class.

The syntax is as follows:

public final int hashCode()
public final int hashCode()

// program  demonstrating the hashCode() method
enum Cities
{
	London, Austin, Manchester;
}

public class hashCodeTest
{

	public static void main(String[] args)
	{
		Cities cOne = Cities.RED;
		System.out.print("hashcode of enum constant "+ cOne.name() +" : ");

		// hashcode method
		System.out.println(cOne.hashCode());
		
		Cities cTwo = Cities.GREEN;
		System.out.print("hashcode of enum constant "+ cTwo.name() +" : ");

		// hashcode method
		System.out.println(cTwo.hashCode());
	}
}

final int compareTo(E obj)

This method “compares” the order of this enum with the provided object. Only other enum constants of the same enum type can be compared to enum constants.

The syntax of compareTo is as follows:

public int compareTo(E obj)
// program  demonstrating the compareTo() method
enum Cities
{
	London, Austin, Manchester;
}

public class Test
{
	// Driver method
	public static void main(String[] args)
	{
		Cities cOne = Cities.RED;
		Cities cTwo = Cities.GREEN;
		Cities cThree = Cities.RED;
		Cities cFour = Cities.BLUE;
		
		System.out.print("Comparing "+cOne.name()+" with "+ cTwo.name() +" : ");
		
		// compareTo method
		System.out.println(cOne.compareTo(cTwo));
		
		System.out.print("Comparing "+cOne.name()+" with "+ cThree.name() +" : ");
		
		// compareTo method
		System.out.println(cOne.compareTo(cThree));
		
		System.out.print("Comparing "+cFour.name()+" with "+ cTwo.name() +" : ");
		
		// compareTo method
		System.out.println(cFour.compareTo(cTwo));
		
		// The following statement throw NullPointerException
		// as argument of compareTo method is null
		// System.out.println(cFour.compareTo(null));
		
	}
}

static T valueOf(Class enumType,String name)

This function returns the name of the enum constant of the supplied enum type. An identifier used to declare an enum constant in this type must exactly match the name.

The syntax is as follows:

public static T valueOf(Class enumType,String name)
// program  demonstrating the valueOf() method
enum Cities
{
	London, Austin, Manchester;
}
public class valueOfTest
{

	public static void main(String[] args)
	{
		// getting value of enum with specified String
		// using valueOf method
		Cities cOne = Cities.valueOf("London");
		Cities cTwo = Cities.valueOf("Austin");
		
		// name method
		System.out.println(cOne.name());
		System.out.println(cTwo.name());
		
		// The following statement throw IllegalArgumentException
		// as LoNDON is not an enum constant
		// Cities cThree = Cities.valueOf("LoNDON");
		
		// The following statement throw NullPointerException
		// as argument of valueOf method is null
	// Cities cFour = Cities.valueOf(null);
	}
}

final Class getDeclaringClass()

This function returns the Class object for the enum type of this enum constant. If this function returns the same Class object for both enum constants e1 and e2, they are of the same enum type.

The syntax is as follows:

public final Class getDeclaringClass()
// program  demonstrating the getDeclaringClass() method
enum Cities
{
	London, Austin, Manchester;
}

enum Month
{
	JANUARY, FEBRUARY ;
}

public class getDeclaringClassTest
{
	// Driver method
	public static void main(String[] args)
	{
		// getting value of enum with specified String
		// using valueOf method
		Cities c1 = Cities.valueOf("London");
		Cities c2 = Cities.valueOf("Austin");
		Month mOne = Month.valueOf("JANUARY");
		Month mTwo = Month.valueOf("FEBRUARY");
		
		System.out.print("Class corresponding to "+ c1.name() +" : ");
	
		// getDeclaringClass method
		System.out.println(cOne.getDeclaringClass());
		
		System.out.print("Class corresponding to "+ cTwo.name() +" : ");
		
		// getDeclaringClass method
		System.out.println(cTwo.getDeclaringClass());
		
		System.out.print("Class corresponding to "+ mOne.name() +" : ");
		
		// getDeclaringClass method
		System.out.println(mOne.getDeclaringClass());
		
		System.out.print("Class corresponding to "+ mTwo.name() +" : ");
		
		// getDeclaringClass method
		System.out.println(mTwo.getDeclaringClass());
	}
}

final Object clone()

This function ensures that enums are never cloned, which is required to keep them “singleton.” It’s utilized by the compiler to generate Enum constants.

The syntax is as follows:

public final Object clone() throws CloneNotSupportedException
// program  demonstrating the clone() method
enum Cities
{
	London, Austin, Manchester;
}

public class cloneTest
{
	// Driver method
	public static void main(String[] args)
			throws CloneNotSupportedException
	{
		System.out.println("Enums are never cloned");
		cloneTest tClone = new cloneTest()
		{
			// final clone method
			protected final Object clone()
					throws CloneNotSupportedException
			{
				return new CloneNotSupportedException();
			}
		};
		
		System.out.println(tClone.clone());
	}
}

final void finalize()

Enum classes cannot have finalize method, according to this method.

The syntax is as follows:

protected final void finalize()
// program  demonstrating the finalize() method
enum Cities
{
	London, Austin, Manchester;
}

public class finalizeTest
{

	public static void main(String[] args) throws Throwable
	{
		System.out.println("enum classes cannot have finalize methods");
		finalizeTest tVal = new finalizeTest()
		{
			// final finalize method
			protected final void finalize() throws Throwable
			{
				// empty implementation
			};		
		};
	}
}

Conclusion

We’ve explored how to use the valueOf method in Java in this Java Enum valueOf example. Because every enum in Java inherently extends java.lang, the valueOf method is available to all Java Enum. Enum is a type of class. The enum valueOf method receives the exact String used to declare the Enum constant and returns that Enum constant. IllegalArgumentException is thrown if the valueOf method returns an invalid String.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *