Comparing Enumeration Values in Java

Java 8Object Oriented ProgrammingProgramming

To compare enumeration values, use the equals() method.

Our Devices enum is having some objects with values assigned to them.

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

Let us compare them −

if(d3.equals(Devices.TABLET))
System.out.println("Devices are same.");
else
System.out.println("Devices are different.");

The following is an example −

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.equals(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:20:53
Advertisements