www.000webhost.com
/** * Created by PhpStorm. * User: Rahul * Date: 12/8/2016 * Time: 8:09 PM */ Enum - Java Java Tech Tutorials



Previous Page




ENUM in Java

Core Java

We can use enum to define a group of named constants. The main purpose of “enum” is to define our own data types. It is introduced in 1.5v. Internally its implemented by using class concept. Every enum constant is public, static and final.
For example :-

	
	 //enum Beer {  KF,RC;  } is internally implemented by
	
	class Beer {
	
	public static final Beer KF = new Beer();
	
	public static final Beer RC = new Beer(); 
	
	}
	
enum Beer
{
	KF,RC,KO,FO;
}
class  EnumDemo1
{
	public static void main(String[] args) 
	{
		Beer b = Beer.RC;
		System.out.println(b);
	}}
	// Output:-
	 RC

We can declare enum either within a class or outside class but we cannot declare it inside a method.

How to use Enum in Switch

We can pass enum as an argument to switch statement.

enum Beer
{
	KF,RC,KO,FO;
}
class EnumDemo2
{
	public static void main(String[] args) 
	{
		Beer b = Beer.RC;
		switch(b)
		{
			case KF:
			System.out.println("Kids Stuff!");
			break;
	 
			case RC:
			System.out.println("Its Ok!");
			break;
	 
			case KO:
			System.out.println("I am knocked out !");
			break;
	 
			case FO:
			System.out.println("r u kidding me ?");
			break;
	 
			default:
			System.out.println("Rest are not good!");
		}
	}
}

Enum in switch - Example

enum Beer
{
	KF,KO,RC,FO;
}

class EnumDemo3
{
	public static void main(String[] args) 
	{
		Beer[] b = Beer.values();
		for(Beer b1: b)	
		{
			System.out.println(b1 + ".................. " +b1.ordinal());
		}
	}
}

	Output :-
	 KF.................. 0
	 KO.................. 1
	 RC.................. 2
	 FO.................. 3

We can define methods, constructors, variables inside an enum



enum Fish 
{
	STAR,GOLD,GUPPY;
	public static void main(String[] args) 
	{
		System.out.println("Enum Main Method!");
	}
}

Output
	Enum Main Method!
	

An enum can contain constructors :-



Enum constructor will be executed for every constant separately at time of class loading.

enum Beer
{
	KF,KO,RC,FO;	
 
	Beer()
	{
		System.out.println("In Enum Constructor!");
	}
}
class Test
{
	public static void main(String[] args) 
	{
		Beer b = Beer.RC;
		System.out.println("IN Main");
	}
}

Ckick Me


Click here to access OOp's Concept

feel free to ask any of your doubts