Comparing Enums

13 February 2012 By Nithya Vasudevan 356 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×

We can use either == or equals() method to compare enum values.
Example:
Both the ‘if’ statements in the below code are equivalent.

package com.ibytecode.enums;

public class Pizza {

	enum PizzaSize
	{
		SMALL, MEDIUM, LARGE
	};
	
	PizzaSize size;
	
	public static void main(String[] args) {
		Pizza pizza = new Pizza();
		pizza.size = PizzaSize.LARGE;

		if(pizza.size.equals(PizzaSize.LARGE)) {
			System.out.println("SIZE == LARGE");
		}
		
		if(pizza.size == PizzaSize.LARGE) {
			System.out.println("SIZE EQUALS LARGE");
		}
		
		System.out.println("Pizza Size is " + pizza.size);
	}

}

SIZE == LARGE
SIZE EQUALS LARGE
Pizza Size is LARGE

Tags: , , , , , ,