The valueOf() method of TimeUnit Class returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
Syntax:
public static TimeUnit valueOf(String name)
Parameters: This method accepts a mandatory parameter name which is the name of the enum constant to be returned.
Return Value: This method returns the enum constant with the specified name
Exception: This method throws following exceptions:
- IllegalArgumentException– if this enum type has no constant with the specified name
- NullPointerException– if the argument is null
Below program illustrate the implementation of TimeUnit valueOf() method:
Program 1:
import java.util.concurrent.*;
class GFG {
public static void main(String args[])
{
TimeUnit Days = TimeUnit.valueOf( "DAYS" );
System.out.println( "TimeUnit object "
+ "is of type: "
+ Days);
System.out.println( "1 Day = "
+ Days.toHours( 1 )
+ " Hours" );
}
}
|
Output:
TimeUnit object is of type: DAYS
1 Day = 24 Hours
Program 2: To demonstrate NullPointerException
import java.util.concurrent.*;
class GFG {
public static void main(String args[])
{
try {
System.out.println( "Trying to create "
+ "TimeUnit object "
+ "using null Enum type" );
TimeUnit Days = TimeUnit.valueOf( null );
}
catch (NullPointerException e) {
System.out.println( "\nException thrown: " + e);
}
}
}
|
Output:
Trying to create TimeUnit object using null Enum type
Exception thrown: java.lang.NullPointerException: Name is null
Program 3: To demonstrate IllegalArgumentException
import java.util.concurrent.*;
class GFG {
public static void main(String args[])
{
try {
System.out.println( "Trying to create "
+ "TimeUnit object "
+ "using ABCD Enum type" );
TimeUnit Days = TimeUnit.valueOf( "ABCD" );
}
catch (IllegalArgumentException e) {
System.out.println( "\nException thrown: " + e);
}
}
}
|
Output:
Trying to create TimeUnit object using ABCD Enum type
Exception thrown: java.lang.IllegalArgumentException: No enum constant java.util.concurrent.TimeUnit.ABCD