Java Program to use == operator to compare enums


We can use the == operator to compare enums in Java.

Let’s say we have the following enum.

enum Devices {
   LAPTOP, MOBILE, TABLET;
}

Here are some of the objects and we have assigned some values as well −

Devices d1, d2, d3;
d1 = Devices.LAPTOP;
d2 = Devices.LAPTOP;
d3 = Devices.TABLET;

Let us now see an example wherein we will compare them using == operator −

Example

 Live Demo

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

Output

Devices are same.
Devices are same.

Updated on: 29-Jun-2020

96 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements