Showing posts with label TimeUnit constants. Show all posts
Showing posts with label TimeUnit constants. Show all posts

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

values : Return all TimeUnit constants

public static TimeUnit[] values()
Returns an array containing the constants of this enum type, in the order they are declared.

import java.util.concurrent.TimeUnit;
public class TimeUnitEx {
 public static void main(String args[]){
  TimeUnit[] t;
  t = TimeUnit.values();
  System.out.println("The constants defined in TimeUnit Class are");
  for(int i=0; i<t.length; i++)
   System.out.println(t[i]);
 }
}

Output
The constants defined in TimeUnit Class are
NANOSECONDS
MICROSECONDS
MILLISECONDS
SECONDS
MINUTES
HOURS
DAYS

Related Posts




TimeUnit Class                                                 Get value of Time constant                                                 Home