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

Java 8Object Oriented ProgrammingProgramming

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.
raja
Published on 20-Dec-2018 05:16:27
Advertisements