In this example we will show how to use enum in Java.
Source Code
1)Start by creating an enumerated type
package com.beginner.examples;
public enum Operation {
PLUS, MINUS, TIMES, DIVIDE;
double calculate(double x, double y) {
switch (this) {
case PLUS:
return x + y;
case MINUS:
return x - y;
case TIMES:
return x * y;
case DIVIDE:
return x / y;
default:
throw new AssertionError("Unknown operations " + this);
}
}
}
2)
package com.beginner.examples;
public class EnumExample1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(Operation.DIVIDE);
}
}
output:
DIVIDE
3)
package com.beginner.examples;
public class EnumExample2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
double result = Operation.PLUS.calculate(2, 6);
System.out.println(result);
}
}
output:
8.0