The equals and == operator for Enum data type in Java


We have the Devices Enum with four constants.

enum Devices {
LAPTOP, MOBILE, TABLET, DESKTOP;
}

We have created some objects and assigned them with the constants.

Let us compare them with both equals() and ==. Firstly, begin with equals() −

if(d1.equals(d2))
System.out.println("Devices are the same.");
else
System.out.println("Devices are different.");

Now, let us move forward and check for ==

if(d1 == d3)
System.out.println("Devices are the same.");
else
System.out.println("Devices are different.");

The following is the final example demonstrating both equals() and == operator −

Example

 Live Demo

public class Demo {
   enum Devices {
      LAPTOP, MOBILE, TABLET, DESKTOP;
   }
   public static void main(String[] args) {
      Devices d1, d2, d3, d4;
      d1 = Devices.LAPTOP;
      d2 = Devices.LAPTOP;
      d3 = Devices.TABLET;
      d4 = Devices.DESKTOP;
      if(d1.equals(d2))
         System.out.println("Devices are the same.");
      else
         System.out.println("Devices are different.");
      if(d1 == d3)
         System.out.println("Devices are the same.");
      else
         System.out.println("Devices are different.");
   }
}

Output

Devices are the same.
Devices are different.

Updated on: 29-Jun-2020

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements