Comparing enum members in Java


The java.lang.Enum class is the common base class of all Java language enumeration types.

Class Declaration

Following is the declaration for java.lang.Enum class -

public abstract class Enum<E extends Enum<E>>
   extends Object
      implements Comparable<E>, Serializable

We can compare enum variables using the following ways.

  • Using Enum.compareTo() method. compareTo() method compares this enum with the specified object for order.

  • Using Enum.equals() method. equals() method returns true if the specified object is equal to this enum constant.

  • Using == operator. The == operator checks the type and makes a null-safe comparison of the same type of enum constants.

Example

Live Demo

public class Tester {
   // enum showing topics covered under Tutorials
   enum Tutorials {        
      TOPIC_1, TOPIC_2, TOPIC_3;    
   }  

   public static void main(String[] args) {
      Tutorials t1, t2, t3;
 
      t1 = Tutorials.TOPIC_1;        
      t2 = Tutorials.TOPIC_2;        
      t3 = Tutorials.TOPIC_3;  

      //Comparing using compareTo() method
      if(t1.compareTo(t2) > 0) {
         System.out.println(t2 + " completed before " + t1);        
      }

       if(t1.compareTo(t2) < 0) {
         System.out.println(t1 + " completed before " + t2);        
      }

      if(t1.compareTo(t2) == 0) {          
         System.out.println(t1 + " completed with " + t2);        
      }

      //Comparing using ==      
      //In this case t1 can be null as well causing no issue
      if(t1 == Tutorials.TOPIC_1) {
         System.out.println("t1 = TOPIC_1");
      }else {
         System.out.println("t1 != TOPIC_1");
      }

      //Comparing using equals() method
      //In this case t2 cannot be null. It will cause
      //null pointer exception
      if(t2.equals(Tutorials.TOPIC_2)) {
         System.out.println("t2 = TOPIC_2");
      }else {
         System.out.println("t2 != TOPIC_2");
      }

      Tutorials t4 = null;  
      //Comparing using equals() method
      //in null safe manner
      if(Tutorials.TOPIC_3.equals(t4)) {
         System.out.println("t4 = TOPIC_3");
      }else {
         System.out.println("t4 != TOPIC_3");
      }          
   }
}

Output

TOPIC_1 completed before TOPIC_2
t1 = TOPIC_1
t2 = TOPIC_2
t4 != TOPIC_3

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 18-Jun-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements