Java – Compare Enum value

In Java, you can use == operator to compare Enum value.

1. Java Enum example

Language.java

package com.mkyong.java

public enum Language {
    JAVA,
    PYTHON,
    NODE,
    NET,
    RUBY
}

2. Compare with ==

Example to compare enum value with == operator.

Test.java

package com.mkyong.java

public class Test {

    public static void main(String[] args) {

		// Covert string to enum
        //Language enumObj = Language.valueOf("java".toUpperCase());

        Language enumObj = Language.JAVA;
		
        if (enumObj == Language.JAVA) {
            System.out.println("Welcome Java");
        } else if (enumObj == Language.NET) {
            System.out.println("Welcome .Net");
        } else if (enumObj == Language.NODE) {
            System.out.println("Welcome Node JS");
        } else if (enumObj == Language.PYTHON) {
            System.out.println("Welcome Python");
        } else if (enumObj == Language.RUBY) {
            System.out.println("Welcome Ruby");
        } else {
            System.out.println("Hello World");
        }

    }

}

Output

Welcome Java

3. Compare with Switch

Alternatively, you can compare enum value with switch statement.

Test.java

package com.mkyong.java

public class Test {

    public static void main(String[] args) {

        Language enumObj = Language.PYTHON;

        switch (enumObj) {
            case JAVA:
                System.out.println("Welcome Java");
                break;
            case NET:
                System.out.println("Welcome .Net");
                break;
            case NODE:
                System.out.println("Welcome Node JS");
                break;
            case PYTHON:
                System.out.println("Welcome Python");
                break;
            case RUBY:
                System.out.println("Welcome Ruby");
                break;
            default:
                System.out.println("Hello World");
                break;
        }

    }

}

Output

Welcome Python

References

  1. Oracle Doc – Enum Types
  2. Java – Convert String to Enum object
  3. Stackoverflow – Comparing Java enum members: == or equals ()
author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
3000