Java Program to use == operator to compare enums

Java 8Object Oriented ProgrammingProgramming

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