Enums in Java

It is like a class where we define constants. We can declare constants using final keyword but it is not meaningful. So we use enums. Enums are also type-safe. Another advantage of using Enum is that we can declare methods as well as constructors in Enum.

Below example demonstrates how we can use Enums in Java. We have created 2 Enums with names Coins and CoinsWithMethods. Since Enums are constant expressions, we can also use them in switch statement.

package enums;

/**
 * Created by ssalunke on 13/04/2016.
 */
public class TestEnums {

    public static void main(String [] args){

        Coins c = Coins.FIVE;

        //We can use enum in Switch statement as shown in below code
        switch (c) {
            case ONE:
                System.out.println("You selected Coin type - ONE");
                break;
            case FIVE:
                System.out.println("You selected Coin type - FIVE");
                break;
            case TEN:
                System.out.println("You selected Coin type - TEN");
                break;
        }

        CoinsWithMethods c1 = CoinsWithMethods.FIVE;

        //below line accesses the method of enum
        System.out.println("Year of Coin 5 is - > " + c1.getCoinYear());
  }

}

enum Coins{
    ONE,
    FIVE,
    TEN
}

enum CoinsWithMethods {
    ONE(2002),
    FIVE(2005),
    TEN(2007);

    private int coinYear;

    private CoinsWithMethods(int a){
        coinYear = a;
    }

    int getCoinYear(){
        return this.coinYear;
    }

}

Here is the output of above code.
You selected Coin type – FIVE
Year of Coin 5 is – > 2005

You may also like...