java tutorial

java tutorial

Java Enum and Annotation

Enum and Annotation

Annotations are basically a method for adding metadata to code which don’t hamper the capacity of the code, however just basically adds data to it. You can put them before class definitions, field definitions, and strategy declarations to give the explained question a smidgen of data. E.g.,

  • @Override before the declaration of the method or any field
  • @Deprecated can be added before anything to mark any field or method or any class to be deprecated

Enumerated types are used to represent a fixed collection of constants just like predefined constant- static final can be used before class which changes the handling mechanism of the class.

Enum is a keyword in JAVA which can replace class keyword while defining its type. E.g.,

 

public class Enums
{
    public static void main(String[] args)
    {
        for (EnumParams e : EnumParams.values()) // foreach loop 
        {
            System.out.println(e.getNumber());
        }
        WithoutParams number = WithoutParams.TWO;
        switch (number) // switch statement 
        {
        case ONE:
            System.out.println("1");
            break;
        case TWO:
            System.out.println("2");
            break;
        case THREE:
            System.out.println("3");
            break;
        case FOUR:
            System.out.println("4");
            break;
        case FIVE:
            System.out.println("5");
            break;
        }
    }
}
enum EnumParams // enum with a constructor
{
    ONE(1),
    TWO(2),
    THREE(3),
    FOUR(4),
    FIVE(5);

    private int number; // enum field,

    private EnumParams(int par1) // private; enum constructor
    {
        this.number = par1;
    }
    public int getNumber() // enum method
    {
        return this.number;
    }
}
enum WithoutParams // without a constructor
{
    ONE,
    TWO,
    THREE,
    FOUR,
    FIVE;
}

 

Output: 1

2

3

4

52

Leave a Reply

Your email address will not be published. Required fields are marked *