Enum Methods in Java

Java 8Object Oriented ProgrammingProgramming

Let us learn about some of the methods in Java.

Enum ordinal() method

Get the ordinal of an enumeration constant in Java using ordinal() method in Java.

The following is an example −

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;
      System.out.println("Ordinal Values...");
      for(Devices d : Devices.values()) {
         System.out.print(d+" = ");
         System.out.println(d.ordinal());
      }
   }
}

Output

Ordinal Values...
LAPTOP = 0
MOBILE = 1
TABLET = 2
DESKTOP = 3

Enum equals() method

It returns true if the specified object is equal to this enum constant.

Let us see 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.");
   }
}

Output

Devices are same.
raja
Published on 20-Dec-2018 05:41:58
Advertisements