Saturday, 10 June 2017

Java Tutorial: Enum in java | Java enum [How to convert String to Enum - Operation] ~ foundjava


Click here to watch in Youtube : 

https://www.youtube.com/watch?v=4m1v7CnUesc&list=UUhwKlOVR041tngjerWxVccw

Operation.java

public enum Operation
{
    PLUS, MINUS, MULTIPLY, DIVIDE;

    long calculate(long x, long y)
    {
        switch (this)
        {
        case PLUS:
            return x + y;
        case MINUS:
            return x - y;
        case MULTIPLY:
            return x * y;
        case DIVIDE:
            return x / y;
        default:
            throw new AssertionError("Unknown operations " + this);
        }
    }

}
EnumDemo.java
public class EnumDemo
{
    public static void main(String[] args)
    {
        /*
         * Convert a String to Enum object.
         */
        Operation operation = Operation.valueOf("plus".toUpperCase());
        System.out.println(operation);
        
        System.out.println(operation.calculate(10, 20));
    }
}
Output
PLUS
30
Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment