Java.lang Package Classes

Java Enum - compareTo() Method



The java.lang.Enum.compareTo() method is used to compare this enum with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. Enum constants are only comparable to other enum constants of the same enum type.

Syntax

public final int compareTo(E o)

Here, E is the type of element maintained by the container.


Parameters

o Specify the object to be compared.

Return Value

Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Exception

NA.

Example:

In the example below, the java.lang.Enum.compareTo() method is used to compare the given enum with the specified object for order.

import java.lang.*;

public class MyClass {
  
  //creating an enum
  public enum weekday{
    MON, TUE, WED, THU, FRI
  }

  public static void main(String[] args) {
    
    weekday d1, d2, d3;

    d1 = weekday.MON;
    d2 = weekday.TUE;
    d3 = weekday.WED;

    if(d2.compareTo(d1) < 0) {
      System.out.println(d2 + " comes before " + d1);
    } else if ((d2.compareTo(d1) > 0)) {
      System.out.println(d2 + " comes after " + d1);
    } else {
      System.out.println("days are same.");
    }

    if(d2.compareTo(d3) < 0) {
      System.out.println(d2 + " comes before " + d3);
    } else if ((d2.compareTo(d3) > 0)) {
      System.out.println(d2 + " comes after " + d3);
    } else {
      System.out.println("days are same.");
    } 
  }
}

The output of the above code will be:

TUE comes after MON
TUE comes before WED

❮ Java.lang - Enum

5