Friday, 7 March 2014

valueOf(): Return TimeUnit Constant

public static TimeUnit valueOf(String name)
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.

Example
import java.util.concurrent.TimeUnit;
public class TimeUnitEx {
 public static void main(String args[]){
  TimeUnit Days = TimeUnit.valueOf("DAYS");
  System.out.println(Days);
  System.out.println(Days.toHours(1));
 }
}

Output
DAYS
24
   
Some Points to Remember
1. If the argument to the valuesOf is null, then NullPointerException thrown.
import java.util.concurrent.TimeUnit;
public class TimeUnitEx {
 public static void main(String args[]){
  TimeUnit Days = TimeUnit.valueOf(null);
 }
}

When you tries to run the above program, Java run time throws the NullPointerException.

Exception in thread "main" java.lang.NullPointerException: Name is null
 at java.lang.Enum.valueOf(Enum.java:235)
 at java.util.concurrent.TimeUnit.valueOf(TimeUnit.java:71)
 at TimeUnitEx.main(TimeUnitEx.java:14)
Java Result: 1

2. If the string passed to valueOf is not match with the TimeUnit constants, then IllegalArgumentException thrown.
import java.util.concurrent.TimeUnit;
public class TimeUnitEx {
 public static void main(String args[]){
  TimeUnit Days = TimeUnit.valueOf("ABCD");
 }
}
   
When you tries to run the above program, Java run time throws IllegalArgumentException

Exception in thread "main" java.lang.IllegalArgumentException: No enum constant java.util.concurrent.TimeUnit.ABCD
            at java.lang.Enum.valueOf(Enum.java:236)
            at java.util.concurrent.TimeUnit.valueOf(TimeUnit.java:71)
            at TimeUnitEx.main(TimeUnitEx.java:14)
Java Result: 1



Get All TimeUnit constants                                                 TimeUnit Conversion                                                 Home

No comments:

Post a Comment