Java-Enumeration

Enumeration

In its simplest form, an enumeration is a list of named constants. An enumeration is created using the enum keyword. For example, here is a simple enumeration that lists various Fruits varieties :

The identifiers ‘Apple’, ‘Banana’, and so on, are called enumeration constants. Once you have defined an enumeration, you can create a variable of that type. However, even though enumerations define a class type, you do not instantiate an enum using new. Instead, you declare and use an enumeration variable in much the same way as you do one of the primitive types. For example, this declares fru as a variable of enumeration type Fruits :

Because fru is of type Fruits, the only values that it can be assigned are those defined by the enumeration. For example, this assigns fru the value Apple :

Notice that the symbol Apple is preceded by Fruits.

Program

0

Program Source

enum Fruits {
    
    Apple, Banana, Cherry, Date, Elderberry
}

public class Javaapp {

    public static void main(String[] args) {
        
        Fruits fru = Fruits.Apple;
        System.out.println(fru);
        fru = Fruits.Date;
        System.out.println(fru);
    }
}

Leave a Comment