Enum in Java Example

Enum in Java Example

Simple examples to demonstrate Enum in Java.

Simple Enum Example.

package com.code2succeed.enumtest;

public enum Country {
	USA,
	INDIA,
	PAKISTAN,
	UK,
	CANADA
}
Test class for Enum.
package com.code2succeed.enumtest;

public class TestEnum {
	public static void main(String[] args) {
		Country country = Country.USA;
		System.out.println(country);
	}
}
Output
USA

Enum with instance variable

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
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
Name of USA is United States of America

Iterating Enum constants with for loop

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
USA : United States of America
INDIA : India
PAKISTAN : Pakistan
UK : United Kingdom
CANADA : Canada

Convert String in Enum Constant

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
USA : United States of America

Leave a Reply

Your email address will not be published. Required fields are marked *