Java Compare Enum value
By:Roy.LiuLast updated:2019-08-17
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
- Oracle Doc – Enum Types
- Java – Convert String to Enum object
- Stackoverflow – Comparing Java enum members: == or equals ()
From:一号门
Previous:Java builder design pattern example
COMMENTS