Krivalar Tutorials 
Krivalar Tutorials

Java enum type


<<Previous

Next >>





Java Enum Type

enum is a data type to store array of predefined values. enums are only to store fixed set of constants. This means they cannot store values that will change. Also, once a set of values are stored during compile time, No constants can be added to or removed from the set

What does Enum Store?

enum is to be used when you need to store an array of values that is displayed and referenced as a name. This is in contrast to indexes used in a regular array. Each element in enum can be simple values or an object having fields which requires a private constructor to be created to set the values.

enum Example


	public enum ColorsOfRainbow{
	VIOLET, INDIGO, BLUE, GREEN, YELLOW, ORANGE, RED;
	}

	public enum ColorsOfRainbow{
		VIOLET("ee82ee"), INDIGO("4B0082"),
		BLUE("0000ff"), GREEN("00ff00"),
		YELLOW("FFFF00"), ORANGE("ffa500"),
		RED("ff0000");
	}

The above enum code means that variable of the above enum can have only one of the 7 values listed





enum in Java - Example 2


ColorsOfRainbow color = ColorsOfRainbow.INDIGO;

enum - Methods and Constructors

enum can have methods. Enum can have only private constructor to get values assigned to variables in enum. public constructors cannot be used in enum as there is no reason to call these constructors outside the class.

enum in Java - Example 3


public enum ColorsOfRainbow {
	VIOLET("ee82ee"), INDIGO("4B0082"),
	BLUE("0000ff"), GREEN("00ff00"),
	YELLOW("FFFF00"), ORANGE("ffa500"),
	RED("ff0000");

	String colorCode;
	private ColorsOfRainbow(String colorCode){
		this.colorCode =colorCode;
	}
	public String getColorCode(){
		return colorCode;
	}

	public static void main(String a[]){
		ColorsOfRainbow color = ColorsOfRainbow.INDIGO;
		System.out.println(color);
		System.out.println(color.getColorCode());

	}
}

Java Enum Example 3 - Output

INDIGO
4B0082

enum in Java - Example 4


public enum DayVsBusiness {

	//Cost, Discount, Margin
	SUNDAY(10000,5,15),
	MONDAY(20000,5,15), TUESDAY(10000,5,15),
	WEDNESDAY(10000,5,15), THURSDAY(10000,5,15),
	FRIDAY(10000,5,15), SATURDAY(10000,5,15);

	double cost, discount, margin;

	private DayVsBusiness(int cost, int discount,int margin){
		this.cost=cost;
		this.discount=discount;
		this.margin=margin;
	}

	public double netProfit(){
		return cost*(1+discount/100)*(margin/100);
	}

	public static void main(String a[]){
		DayVsBusiness dayVsBusiness = DayVsBusiness.FRIDAY;
		System.out.println(dayVsBusiness);
		System.out.println(dayVsBusiness.netProfit());

		DayVsBusiness dayVsBusinessMonday = DayVsBusiness.MONDAY;
		System.out.println(dayVsBusinessMonday);
		System.out.println(dayVsBusinessMonday.netProfit());
	}
}

enum in Java Example 4 Output

FRIDAY
1575.0
MONDAY
3150.0

<<Previous

Next >>





















Searching using Binary Search Tree