Enum compareTo() in Java

compareTo(): This method is available in java.lang.Enum class of Java.

Syntax:

int java.lang.Enum.compareTo(Colour o)

This method takes one argument as its parameter. This method compares 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.

Note: Enum constants are only comparable to other enum constants of the same enum type.

Parameters: One parameter is required for this method.

o: the object to be compared.

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

Exceptions: NA

Approach

Java

enum Colour {
    RED, GREEN, GRAY, ORANGE
}

public class EnumcompareTo {
    public static void main(String[] args) {

        System.out.println(Colour.RED.compareTo(Colour.RED));
    }
}

Output:

0

No comments:

Post a Comment