Java Enum Tutorial | JavaInUse



Enums in Java



Enumerations are list of predefined constants. They represent a group of constants. If we consider a case in a Multiple Choice Questionnaire in which the options are limited i.e A,B,C,D , enum plays a role to make a list of these options (A,B,C,D). Enum is a collection of all these constant values when the outcome is limited.

Syntax of declaring enum in a program is as shown:


Syntax to declare enum

Another example is a list of directions we use namely North, West, South, East. It can be expressed as shown in this code:
Enum Direction{
NORTH, SOUTH, EAST, WEST;    // Mention the constants 
}

The semicolon at the end is not mandatory and is the choice of the coder. According to JAVA conventions constants in enum should be declared in capital letters. It is important to note that we cannot create an object of enum. Enum can be defined as a part of class or outside the class.

Enum used inside a class: -

package com.java1;

public class TestEnum {
	enum FlightBrand{
		Emirates,BritishAirways,AirAsia;
	}
public static void main(String[] args) {
	FlightBrand k = FlightBrand.Emirates;
	System.out.println("The selected Flight Brand is " +k);
}
}


Enum used outside a class: -

package com.java1;

public class TestEnum {
	
public static void main(String[] args) {
	FlightBrand k = FlightBrand.Emirates;
	System.out.println("The selected Flight Brand is " +k);
}
}
enum FlightBrand{
	Emirates,BritishAirways,AirAsia;
}

In both cases the output is
The selected Flight Brand is Emirates


Methods and variables can also be declared inside enum. This property of enum is only available in Java but not in C/C++. This is portrayed in the following example:

package com.java1;

public class TestEnum1 {
	enum AndroidVersion{
		Lolipop(5.0),Oreo(8.0),KitKat(4.4),Marshmallow(6.0);
		double version;
		
		AndroidVersion(double v)
		{
			version = v;
		}
		
		public double getVersion()
		{
			return version;
		}
	
	}
	public static void main(String[] args) {
		System.out.println(AndroidVersion.Lolipop.getVersion());
	}
	

}

First line in the code should be list of constants followed by methods, variables and constructor. Enum can be passed as an argument in switch case:
package com.java1;

public class SwitchEnum {
	enum Color
	{
		RED,GREEN,BLUE
	}
	public static void main(String[] args) {
		
		Color k;
		k = Color.GREEN;
		
		switch(k)
		{
		case RED:
			System.out.println("I am "+k);
			break;
		case GREEN:
			System.out.println("I am "+k);
			break;
		case BLUE:
			System.out.println("I am "+k);
			break;
		
		}	
	}
}
Output:
I am GREEN



Points to remember in Enum





See Also

Overriding equals() in Java Image Comparison in Java Java - PermGen space vs Heap space Java - PermGen space vs MetaSpace Implement Counting Sort using Java + Performance Analysis Java 8 Features Java Miscelleneous Topics Java Basic Topics Java- Main Menu