A Beginner Guide to Enum in Java

Posted By : Rohit Lakra | 30-Nov-2018

What is enum in Java?

If we want to represent a group of named constants than we should go for the enum.
example:- 

       enum Month
       {
       JAN,FEB,MAR,........,DEC;     //semicolon is optional
       }

 

Purpose:-

The main purpose of enum is to define our own datatypes(enumerated datatypes) with our own range of values.

i.e. in pre-defined datatypes like byte, the range is -128 to 127 but by an enum, we can declare values according to our need.

eg:- as in enum Month we are declaring no. of months according to our requirement.

Introduction And Benefits:-

In Java enum concept introduced in 1.5 version. When compared with other languages enum, Java enum is more powerful. 
In Java enum, we can add methods, classes, constructors etc.  

Internal Implementation:-

1. Every enum is internally implemented by using class concept.
2. Every enum constant is always public static final.
3. Every enum constant represents an object of the type enum.

enum Declaration And Usage:-

Every enum constant is always public static final and hence we can access enum constant by using enum name.

example:-

    enum Fruit
    {
    APPLE,MANGO,GRAPES,BANANA;
    }

    class Test
    {
    public static void main(String[] args)
     {
    Fruit f=Fruit.APPLE;
    }
    System.Out.Println(f);
    }
    }

 

Output:- APPLE

 

Note:- 

      We can declare enum either within the class or outside of the class but not inside a method. If we are trying to declare inside a method then we will get a Compile-time       error:- enum types must not be local.

If we declare enum outside of the class the applicable modifiers are 

  • public
  • <default>
  • strictfp

If we declare enum inside a class the applicable modifiers are

  • public
  • default
  • strictfp
  • private 
  • protected 
  • static 

We can also pass enum type as an argument to switch statement.

About Author

Author Image
Rohit Lakra

.

Request for Proposal

Name is required

Comment is required

Sending message..