freetimestudys@gmail.com          +91-7097633380
  Login Here                        

ENUMARATION

1. This concept is introduced in 1.5 version
2. enumeration is used to declare group of named constant s.
3. we are declaring the enum by using enum keyword. For the enums the compiler will generate .classess
4.enum is a keyword and Enum is a class and every enum is directl child class of java.lang.Enum so it is not possible to inherit the some other class. Hence for the enum inheritance concept is not applicable
5. by default enum constants are public static final

enum Week

public static final smantha;
public static final tara;
Public static final ubanu;
}

Enumaration program

enum Heroin
{
samantha,tara,anu;
}
class Test
{
public static void main(String... ratan)
{
Heroin s=Heroin.samantha;
System.out.println(s);
Heroin t=Heroin.tara;
System.out.println(t);
Heroin a=Heroin.anu;
System.out.println(a);
}
};

intput and output

samantha
tara
anu

enumeration methods

1. printing the enumeration constants by using for-each loop.
2. values() methods are used to print all the enum constants.
3. ordinal() is used to print the index values of the enum constants.

enumeration methods ex

enum Heroin
{
samantha,tara,anu;
}
class Test
{
public static void main(String... ratan)
{
Heroin[] s=Heroin.values();
for (Heroin s1:s)
{
System.out.println(s1+"----"+s1.ordinal());
}
}
};

intput and output

samantha----0 tara----1 anu----2

1. inside the enum it is possible to declare constructors. That constructors will be ececuted for each and every constant. If we are declaring 5 constants then 5 times constructor will be executed.
2. Inside the enum if we are declaring only constants the semicolon is optional.
3. Inside the enum if we are declaring group of constants and constructors at that situation the group of constants must be first line of the enum must ends with semicolon.

enumeration constructors program

enum Heroin
{
samantha,tara,anu,ubanu;
Heroin()
{
System.out.println("freetimestudy");
}
}
class Test
{
public static void main(String... ratan)
{
Heroin s=Heroin.samantha;
}
};

intput and output

freetimestudy
freetimestudy
freetimestudy
freetimestudy

constructors with arguments

enum Heroin
{
samantha,tara(100),ubanu(100,200);
Heroin()
{
System.out.println(" smantha constructor");
}
Heroin(int a)
{ System.out.println(a);
System.out.println(" tara constructor");
}
Heroin(int a,int b)
{ System.out.println(a+b);
System.out.println(" ubanu constructor");
}
}
class Test
{
public static void main(String[] args)
{ Heroin[] s=Heroin.values();
for (Heroin s1:s)
{
System.out.println(s1+"--------"+s1.ordinal());
}
}
};

intput and output

smantha constructor
100
tara constructor
300
ubanu constructor
samantha--------0
tara--------1
ubanu--------2