What is Enumeration in Java?-https://vishmy1.blogspot.com/

Enumeration In Java

Enumeration:- It represents a group of named constants in a programming language.

Enums are of class short, by using enum datatype variables of enum can be defined directly without using the new keyword and enum declaration should be done outside a class or inside a class but not inside a method.

the enum keyword is added from JDK 1.5, Enum in java is a data type that contains a fixed set of constants.

 In Java, enumeration defines a class type and can have constructors, methods and instance variables.

It is created by using the enum keyword.

Syntax:-

enum name{constant value_list}

- Each Enumeration constant is public, static and public by default. Even though enumeration defines a class type and have constructors, you can not instantiate an enum using new keyword.

- The variables of the Enumeration are declared and used in much the same way as you do a primitive variable.

Ex:- 

public enum Season{Winter, Summer, Mansoon}
{
    class Enumtest 
    {
        public static void main(String args[])
       {
           for(Season s: Season.values())
           System.out.println(s);
       }
    }
}

Another Example of Enumeration to assign the enum constant value to its own datatype.

enum weekdays{sun, mon, tue, wed, thu, fri, sat}
{
    class Enumtest1 
    {
        public static void main(String args[])
       {
           weekdays wk; //wk is a variable of enumeration type.
           wk = weekdays.sun; //wk can be assigned only the constants of enum type weekdays.
           System.out.println("today is"+wk);
       }
    }
}

Here is another example of Enumeration using switch case.

enum weekdays{sun, mon, tue, wed, thu, fri, sat}
{
    class Enumtest2 
    {
        public static void main(String args[])
       {
           weekdays day;
           day = weekdays.sun;
           case sun : System.out.println("today is sunday");
           case sun : System.out.println("today is monday");
           case sun : System.out.println("today is tuesday");
           case sun : System.out.println("today is wednesday");
           case sun : System.out.println("today is thursday");
           case sun : System.out.println("today is friday");
           case sun : System.out.println("today is saturday");
       }
    }
}


Note:- This blog is for basic knowledge of  Enumeration with Example.

In the next blog, I will explain Enum and Inheritance, enum and constructor, and enum and methods.

If you find anything incorrect in this blog then plz write a comment so that I can provide you a better knowledge.






Post a Comment

0 Comments