Enum Type - Java

Enum type is used to declare the set of constants. It is a special type of data type. The variable must be equal to one of the values in predefined values. Enum types are declared by enum keyword .

Points:

 

Syntax:
public enum type
{
Constants;
}

 

Prgorame on Enum

public class enum1 {

public enum days
{
SUN,MON,TUE,WED,THU,FRI,SAT
}
public static void main(String[] args)
{
System.out.println(days.MON);
days s=days.MON;
System.out.println(s);
for(days d:days.values())
System.out.println(d);
}

}

Note: values() method returns an array of all the values of enum.

Enum can have fields, constructors and methods. we can initialize the specific value to the enum constants by defining fields and constructors.

Program on Enum constants

 

public class enum1 {

            public enum days
{
SUN(1),MON(2),TUE(3),WED(4),THU(5),FRI(6),SAT(7);
int val;
days(int v) // it is a enum constructor
{
val=v;
}
}
public enum metals
{
STEEL(5,1000),ALUMINIUM(7,2000),COPER(3,12000);
int price,tons;
private metals(int t,int p)
{
tons=t;
price=p;
}
}
public static void main(String[] args) {

for(days d:days.values())
System.out.println(d+"  "+d.val);
for(metals m:metals.values())
System.out.println(m+" : Qty "+m.tons+" Rate :"+m.price);
}

}

Program on enum using switch case.

public class enum1
{

public enum fruits
{
APPLE,BANANA,ORANGE,KIWI,GRAPES,PROMOGRANITE;
}
public static void main(String[] args)
{

fruits f=fruits.ORANGE;
switch(f)
{
case APPLE:
System.out.println("Apples ");
break;
case ORANGE:
System.out.println("ORanges");
break;
case BANANA:
System.out.println("Banans");
break;
case KIWI:
System.out.println("Kiwis");
break;
case PROMOGRANITE:
System.out.println("Promogranite");
break;
case GRAPES:
System.out.println("Grapes");
break;
default:
System.out.println("others");
}
}
}

For
More Explanation
&
Online Classes

Contact Us:
+919885348743