Enum ValueOf() In Java Example
Chapter:
Miscellaneous
Last Updated:
13-07-2016 09:09:15 UTC
Program:
/* ............... START ............... */
import java.lang.*;
enum Mobile {
Samsung(400), Nokia(250), Motorola(325);
int price;
Mobile(int p) {
price = p;
}
int showPrice() {
return price;
}
}
public class JavaEnumValueOfExample {
public static void main(String args[]) {
System.out.println("CellPhone List:");
for (Mobile m : Mobile.values()) {
System.out.println(m + " costs " + m.showPrice() + " dollars");
}
Mobile ret;
ret = Mobile.valueOf("Samsung");
System.out.println("Selected : " + ret);
}
}
/* ............... END ............... */
Output
CellPhone List:
Samsung costs 400 dollars
Nokia costs 250 dollars
Motorola costs 325 dollars
Selected : Samsung
Notes:
-
The java.lang.Enum.valueOf() method returns the enum constant of the specified enumtype with the specified name.
- IllegalArgumentException - if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum type.
- NullPointerException -- if enumType or name is null.
Tags
Enum ValueOf(), Miscellaneous, Java