Java Enum Examples

An enum in Java is just like any other class, with a predefined set of instances. Here are several examples to highlight how to use Java Enum.

1. Simple Example

public enum Color {
    RED, YELLOW, BLUE; //each is an instance of Color 
}
public class Test {
	public static void main(String[] args) {
		for(Color color: Color.values()){
			System.out.println(color);
		}
	}
}

Output:

RED
YELLOW
BLUE

2. With Constructor

public enum Color {
    RED(1), YELLOW(2), BLUE(3); //each is an instance of Color 
 
    private int value;
 
    private Color(){}
 
    private Color(int i){
    	this.value = i;
    }
 
    //define instance method
    public void printValue(){
    	System.out.println(this.value);
    }
}
public class Test {
	public static void main(String[] args) {
		for(Color color: Color.values()){
			color.printValue();
		}
	}
}
1
2
3

3. When to Use Java Enum?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.

A good use case is preventing the possibility of an invalid parameter. For example, imagine the following method:

public void doSomethingWithColor(int color);

The method is ambiguous and other developers have no idea about what value to use. If you have an enum Color with BLACK, RED, etc. the signature becomes:

public void doSomethingWithColor(Color color);

The code calling this method will be far more readable.

References:
1. https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Category >> Basics >> Java  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>