ENUM Concept Simplified In Java

0
81
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

enum in java,Enumerated type in java
enum in java

ENUM Concept Simplified In Java or What is Enumerated type?

Java allows us to use enumerated type using the enum keyword.This keyword can be used similar to static final constants.If the programmer wants to represent a group of constants across programming, then they can implement enum
Enumeration. It has been introduced in Java 1.5 (or java 5 or Tiger release)

The main objective of enum is to define our own datatypes like enumerated data types. This is more powerful concept than older java constant.
When an enumerated type is defined inside another class,it is a nested class inside the enclosing class.It is a static nested class irrespective of the declaration.But it can also be declared as non nested class in a file of its own.If a enum is declared in a normal java class we need to add semi colon(;) at the end of the list values.

enum Month
{
JAN,FEB,MAR;
//note semicolon(;) is optional here
}

or let us check a new example

enum Laptop_company
{
Lenevo,DELL,HP;
//note semicolon(;) is optional here
}

Internal Implementation of enum:

  • If we declare a enum in java compiler is going to transform that to a class concept so in the .class file that enum is structured as class. you can see a [enum name.class] file where you have stored your .class file.
  • If we declare element inside enum that is constant. So they are public static and final.
  • Every enum constant is an object of the type enum

Now let us see in practical how it works. Lets us take the first example..

enum Month
{
JAN,FEB,MAR;
//note semicolon(;) is optional here
}

Compiler will transform that in to the class file as..

Class Month
{
//for JAN
public static final Month JAN=new Month();
//similarly for FEB and MAR
public static final Month FEB=new Month();
public static final Month MAR=new Month();
}

Based on the discussion we can say ..
Every enum constant is always static hence we can always access them using enum name

enum Month{
JAN,FEB,MAR;
}
class testenum2
{
public static void main(String... Args)
{
Month m=Month.JAN;
System.out.println(m);
}
}

output: JAN

  • Inside every enum toString() method is internally implemented to return the name of the constant.
  • We can declare enum inside of a class and outside of a class.If we declare inside of a class compiler will treat that as inner class.
    The applicable modifiers are 1. public 2. [default] 3. strictfp 4.private 5. protected 6.static
  • if we put enum outside of the class then compiler will treat it as different class. Hence the modifier would be public,[default],strictfp

so

enum Month{
JAN,FEB,MAR;
}
class testenum2
{
public static void main(String... Args)
{
Month m=Month.JAN;
System.out.println(m);
}
}

This is a valid deceleration

class testenum2
{
enum Month{
JAN,FEB,MAR;
}
public static void main(String... Args)
{
Month m=Month.JAN;
System.out.println(m);
}
}

This is also a valid deceleration.

We can not declare an enum inside of a method. If so, Compiler will throw Compile time exception.

let us check out that example..

class testenum2
{
public static void main(String... Args)
{
Month m=Month.JAN;
System.out.println(m);
}
public static void somemethod();
{
enum Month{
JAN,FEB,MAR;
}
}
}

here well get the compiler error as..
E:myProgramtestenum2.java:11: error: enum types must not be local
enum Month{
^
1 error

When I said new enum is more powerful after 1.5 version of java.In new enum, we can add constant, method, constructor, normal variables.
Even enum can contain main method. We can also invoke enum class directly from command prompt.

enum testenum21
{
JAN,FEB,MAR;
public static void main(String... Args)
{
System.out.println("Runing enum main method");
}
}

output:
C:Documents and Settingsanichatt.APPLICATIONS>javac E:myProgramtestenum21.java
C:Documents and Settingsanichatt.APPLICATIONS>java testenum21
Runing enum main method

  • In addition to constant if other members(methods) other than constant are taken, list of constant should be in the written in the first line.
  • The constants must end with semicolon.
  • No constants are allowed to write after method name.
  • If the enum is having only method inside in, then the firstline should be empty statement(i.e only semi colon)
  • empty enum is valid in java.

let us check the standards one by one..

The first line should be constant deceleration and it must end with semicolon

enum testenum21
{
JAN,FEB,MAR;
public static void somemethod()
{
System.out.println("do something");
}
}

This syntax is valid and semicolon is mandate

Let us check out if we don’t give semicolon what will happen

enum testenum21
{
JAN,FEB,MAR
public static void somemethod()
{
System.out.println("do something");
}
}

The output is :
E:myProgramtestenum21.java:4: error: ‘,’, ‘}’, or ‘;’ expected
public static void somemethod()
^
E:myProgramtestenum21.java:4: error: ‘}’ expected
public static void somemethod()
^
E:myProgramtestenum21.java:7: error: class, interface, or enum expected
}
^
3 errors

Let us see how it behaves with constants to declared after method:

enum testenum21
{
public static void somemethod()
{
System.out.println("do something");
}
JAN,FEB,MAR;
}

The output: Compilation error:
E:myProgramtestenum21.java:2: error: expected
{
^
E:myProgramtestenum21.java:4: error: ‘,’, ‘}’, or ‘;’ expected
public static void somemethod()
^
E:myProgramtestenum21.java:4: error: ‘}’ expected
public static void somemethod()
^
E:myProgramtestenum21.java:7: error: class, interface, or enum expected
}
^
E:myProgramtestenum21.java:9: error: class, interface, or enum expected
}
^
5 errors

Similar compilation error will happen if and only if methods are declared inside enum without blank statement:

enum testenum21
{
public static void somemethod()
{
System.out.println("do something");
}
}

This syntax is also invalid.
The modified version will be something like written below with an empty statement.

enum testenum21
{
;
//this semicolon means an empty statement.
public static void somemethod()
{
System.out.println("do something");
}
}

Also empty enum is valid…

 

enum testenum21
{
}

One more working example:

 


public class WorkingDays{
    enum Days{
        Sunday,Monday,Tuesday,Wednesday,Thrusday,Friday,Saturday
    }
    public static void main(String args[])
    {
        for(Days d:Days.values())
        {
            weekend(d);
        }
    }
    private static void weekend(Days d)
    {
        if(d.equals(Days.Sunday))
        {
            System.out.println("Day Value="+d+"is a holiday");
        }
        else{
                System.out.println("Day Value="+d+"is a working day");
        }
}
}

output of the code:
$javac WorkingDays.java
$java -Xmx128M -Xms16M WorkingDays
Day Value=Sundayis a holiday
Day Value=Mondayis a working day
Day Value=Tuesdayis a working day
Day Value=Wednesdayis a working day
Day Value=Thrusdayis a working day
Day Value=Fridayis a working day
Day Value=Saturdayis a working day

Advantages:

  1. enum provides compile time type safety.
  2. we can use enum keyword in switch statement as constant.

Final points to remember:

  • Every enum is direct child of java.lang.Enum class.
  • It is an abstract class
  • Hence it becomes a base class for java enum
  • This is also a direct child of Object
  • enum implements comparable and serializable interface

How To Get Values from Enum In Java?

There are three ways we can get values from enum..

  • direct way
  • by using values() method
  • by using ordinal() method
Direct Method
enum testenum21
{
JAN,FEB,MAR;
}
class getvalues{
public static void main(String... Args)
{
testenum21 mon=testenum21.JAN;
System.out.println(mon);
}
}

output: JAN

values() Method

We can use values method to get each element from enum.
The syntax is [[enumname]][] variable=[[enumname]].values();

enum testenum21
{
JAN,FEB,MAR;
}
class getvalues{
public static void main(String... Args)
{
testenum21[] mon=testenum21.values();
for(testenum21 m: mon)
{
System.out.println(m);
}
}
}

output:
JAN
FEB
MAR

ordinal() Method

If in our programming order of the enum constant becomes important,we can use ordinal method to get the order of the element.
The syntax is
public final int ordinal();

enum testenum21
{
JAN,FEB,MAR;
}
class getvalues{
public static void main(String... Args)
{
testenum21[] mon=testenum21.values();
for(testenum21 m: mon)
{
System.out.println(m+"..."+m.ordinal());
}
}
}

The output is
JAN…0
FEB…1
MAR…2
The ordinal method is more powerful and starts with zero. It is zero based.

What Is The Difference Between enum,Enum and Enumeration in Java?

enum Enum Enumeration
enum is a keyword which represents a group of named constants Enum is present in java.lang package. It is a parent class of enum. So it acts as a base class for every enum Enumeration is an interface present in java.util package
enum can hold constructor(no argumented and argumented) and methods Enum can not hold the constructor or methods We use this method to get object from collection one by one
Below 1.4 version it was used as a literal and after 1.4 version it becomes group of constants and it is reserved

How To Work With Java Enum In Switch Argument??

In this post I have shared my view about the switch.The expression constants in a switch statement can be an enumerated type.In such case,the constants in the case labels must be values from enumerated type.
Generally we use if when we need to compare small number of (say 2-3) variables,but for big number of condition check it is always better to go for switch statement.
Until java 1.4 version(java4) switch statement used to take byte,short,char and int as argument.
From java1.5(java 5 or tiger) edition switch supports corresponding wrapper classes and enum types.

Java 1.4 java 1.5 java 1.7
byte Byte String
short Short
char Character
int Interger
enum

So after java 1.5 onwards,enum can be passed as a type as an argument to switch statement
lets check out one example:

enum Month
{
 JAN,FEB,MAR;
//declare enum
}
public class enumTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Month mon=Month.MAR;
//create switch statement
switch(mon)
{
case JAN : System.out.println("1st Month");break;
case FEB : System.out.println("2nd Month");break;
case MAR : System.out.println("3rd Month");break;
}
}
}

output:
3rd Month
we can pass enum type as argument to switch statement, but every case label should be Valid enum contant. Otherwise we will get compile time error.

enum Month
{
 JAN,FEB,MAR;
//declare enum
}
public class enumTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Month mon=Month.MAR;
//create switch statement
switch(mon)
{
case JAN : System.out.println("1st Month");break;
case FEB : System.out.println("2nd Month");break;
case MAR : System.out.println("3rd Month");break;
case APR : System.out.println("4th Month");break;
}
}
}

Output:
Compilation error:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
APR cannot be resolved or is not a field
^
at enumTest.main(enumTest.java:20)
In case of enum context,we can use the enum values directly instead of enum.value.JVM will know that these values are coming from enum.

How Constructor Works In Java Enum ?
How Constructor Works In Java Enum ?

How Constructor Works In Java Enum ?

I have discussed concepts on Enum. In this post I would like to show the constructor concept in java enum.Constructor!!! that too in enum???
Yes!!! java has come up with this beautiful concept.
enum can contain constructors. This constructors will be executed at the time of enum class loading automatically for every enum constant.

enum Month    
{    
JAN,FEB,MAR;    
//note semicolon(;) is optional here    
Month()
{
System.out.println("enum constructor");
}
} 
class Testenumcons{
public static void main(String... Args)
{
Month mon=Month.JAN;
System.out.println("Main method");
}
}

output:
enum constructor
enum constructor
enum constructor
Main method
Now we can also conclude-
we can not create enum object explicitly if we do so we will get compile time error.

enum Month    
{    
JAN,FEB,MAR;    
//note semicolon(;) is optional here    
Month()
{
System.out.println("enum constructor");
}
} 
class Testenumcons{
public static void main(String... Args)
{
Month mon=new Month();
//illegal statement.
Month mon=Month.JAN;
System.out.println("Main method");
}
}

E:myProgramTestenumcons.java:13: error: enum types may not be instantiated
Month mon=new Month();
^
E:myProgramTestenumcons.java:14: error: variable mon is already defined in method main(String…)
Month mon=Month.JAN;
^
2 errors
So we can not invoke enum constructor directly.
Till now in the above example we have seen no argument constructor.But we can also have argumented constructor.

enum Month    
{    
JAN(31),FEB(28),MAR(31),APR;   
int days ;
//note semicolon(;) is optional here  
//argumented constructor  
Month(int days)
{
System.out.println("enum argumented constructor ");
this.days=days;
}
// no argumented constructor
Month()
{
System.out.println("enum no argument constructor");
this.days=31;
}
public int getDays()
{
return days;
}
} 
class Testenumcons{
public static void main(String... Args)
{
Month[] mon=Month.values();
for (Month m:mon)
{
System.out.println(m+"-->"+m.getDays());
}
}
}

output:
enum argumented constructor
enum argumented constructor
enum argumented constructor
enum no argument constructor
JAN–>31
FEB–>28
MAR–>31
APR–>31
In general if you do not define any no argument constructor, Compiler will automatically put a no argument constructor inside enum when it transfer enum to class. but that will have no statement inside it. But there are two cases to check out..
Case 1. if the enum constants have mix with argumented and non argumented then it is compulsory to define both argumented and non argumented constructor. Otherwise compiler will throw compile time error.
Case-2 Compiler will automatically add no argumented constructor if no argumented constructor is defined.

enum Month    
{    
JAN(31),FEB(28),MAR(31),APR;   
int days ;
//note semicolon(;) is optional here  
//argumented constructor  
Month(int days)
{
System.out.println("enum argumented constructor ");
this.days=days;
}
// no argumented constructor
public int getDays()
{
return days;
}
}
class Testenumcons{
public static void main(String... Args)
{
Month[] mon=Month.values();
for (Month m:mon)
{
System.out.println(m+"-->"+m.getDays());
}
}
}

E:myProgramTestenumcons.java:3: error: constructor Month in enum Month cannot
be applied to given types;
JAN(31),FEB(28),MAR(31),APR;
^
required: int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Also inside enum we can add methods. But the methods should be concrete,not abstract.
Every enum constant represents an object of the type enum so the calling of the methods are same as the way we call normal methods
Possible operators we can use are–

  • enum.constantname.equals(enum.constantname)
  • enum.constantname==enum.constantname
  • enum.constantname.ordinal>enum.constantname.ordinal

Normal methods in enum

 

enum testenum21
{
JAN,FEB,MAR;
public void info()
{
System.out.println("enum info method called");
}
}

class getvalues{
public static void main(String… Args)
{
testenum21[] mon=testenum21.values();
for(testenum21 m: mon)
{
System.out.print(m.ordinal()+ ” “);
m.info();
}
}
}

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

LEAVE A REPLY

Please enter your comment!
Please enter your name here