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:
- enum improves type safety
- enum can be easily used in switch
- enum can be traversed
- enum can have fields, constructors and methods
- enum may implement many interfaces but cannot extend any class because it internally extends Enum class
- An enum can be declared outside or inside a class, but NOT in a method.
- An enum declared outside a class must NOT be marked static, final , abstract, protected , or private
- enum constants can send arguments to the enum constructor, using the syntax SUNDAY(7), where the int literal 7 is passed to the enum constructor.
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
More Explanation
&
Online Classes
Contact Us:
+919885348743
+919885348743