Enum uses in Java

Enum uses in Java

There are some advantages of Enum in Java which we have discussed in enum in java. We can use enum in various ways in java, here are some common uses.

  1. In if condition.
  2. In Switch block
  3. Segregating business logic

Simple Enum

package com.code2succeed.enumtest;

public enum Country {
	USA,
	INDIA,
	PAKISTAN,
	UK,
	CANADA
}

1) In if condition

package com.code2succeed.enumtest;

public class TestEnum {
	public static void main(String[] args) {
		Country country = Country.INDIA;
		
		if(Country.CANADA == country) {
			System.out.println("Band is performing in Canada");
		}else if(Country.USA == country) {
			System.out.println("Band is performing in USA");
		}else if(Country.INDIA == country) {
			System.out.println("Band is performing in India");
		}else if(Country.PAKISTAN == country) {
			System.out.println("Band is performing in Pakistan");
		}else if(Country.UK == country) {
			System.out.println("Band is performing in UK");
		}
	}
}
output
Band is performing in India

2) In Switch block

package com.code2succeed.enumtest;

public class TestEnum {
	public static void main(String[] args) {
		Country country = Country.UK;
		
		switch(country) {
			case CANADA :
				System.out.println("Band is performing in Canada");
				break;
			case USA :
				System.out.println("Band is performing in USA");
				break;
			case INDIA :
				System.out.println("Band is performing in India");
				break;
			case PAKISTAN :
				System.out.println("Band is performing in Pakistan");
				break;
			case UK :
				System.out.println("Band is performing in UK");
				break;	
		}
	}
}
Output
Band is performing in UK

3) Segregating business logic

package com.code2succeed.enumtest;

public enum Country {
	USA("United States of America", 36.8),
	INDIA("India", 30.5),
	PAKISTAN("Pakistan", 33.6),
	UK("United Kingdom", 37),
	CANADA("Canada", 32);
	
	private String name;
	private double averageAge;
	private Country(String name, double averageAge) {
		this.name = name;
		this.averageAge = averageAge;
	}
	public String getName() {
		return name;
	}
	public double getAverageAge() {
		return averageAge;
	}
	public static double calcalateAverageAge() {
		double totalAge = 0;
		for(Country country : Country.values()) {
			totalAge += country.averageAge;
		}
		
		double avgAge = totalAge/Country.values().length;
		return avgAge;
	}
}
Test class
package com.code2succeed.enumtest;

public class TestEnum {
	public static void main(String[] args) {
		System.out.println("Combined average age of all countries : "+Country.calcalateAverageAge());
	}
}
Output
Combined average age of all countries : 33.98

Leave a Reply

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