Enum in Java Example
Simple examples to demonstrate Enum in Java.
Simple Enum Example.
1 2 3 4 5 6 7 8 9 |
package com.code2succeed.enumtest; public enum Country { USA, INDIA, PAKISTAN, UK, CANADA } |
Test class for Enum.
1 2 3 4 5 6 7 8 |
package com.code2succeed.enumtest; public class TestEnum { public static void main(String[] args) { Country country = Country.USA; System.out.println(country); } } |
Output
1 |
USA |
Enum with instance variable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.code2succeed.enumtest; public enum Country { USA("United States of America"), INDIA("India"), PAKISTAN("Pakistan"), UK("United Kingdom"), CANADA("Canada"); private String name; private Country(String name) { this.name = name; } public String getName() { return name; } } |
Test class
1 2 3 4 5 6 7 8 |
package com.code2succeed.enumtest; public class TestEnum { public static void main(String[] args) { Country country = Country.USA; System.out.println("Name of "+country+" is "+country.getName()); } } |
Output
1 |
Name of USA is United States of America |
Iterating Enum constants with for loop
1 2 3 4 5 6 7 8 9 10 |
package com.code2succeed.enumtest; public class TestEnum { public static void main(String[] args) { Country [] countries = Country.values(); for(Country country : countries) { System.out.println(country+" : "+country.getName()); } } } |
Output
1 2 3 4 5 |
USA : United States of America INDIA : India PAKISTAN : Pakistan UK : United Kingdom CANADA : Canada |
Convert String in Enum Constant
1 2 3 4 5 6 7 8 9 |
package com.code2succeed.enumtest; public class TestEnum { public static void main(String[] args) { String str = "USA"; Country country = Country.valueOf(str); System.out.println(country+" : "+country.getName()); } } |
Output
1 |
USA : United States of America |