VOOZH about

URL: https://www.geeksforgeeks.org/java/difference-between-ordinal-and-compareto-in-java-enum/

⇱ Difference Between ordinal() and compareTo() in Java Enum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Difference Between ordinal() and compareTo() in Java Enum

Last Updated : 23 Jul, 2025

Enumerations serve the purpose of representing a group of named constants in a programming language. If we want to represent a group named constant then we should go for Enum. Every enum constant is static. Hence, we can access it by using enum Name.

Example:

enum Day{
 SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}

ordinal() Method

The java.lang.Enum.ordinal() tells about the ordinal number(it is the position in its enum declaration, where the initial constant is assigned an ordinal of zero) for the particular enum.

ordinal() method is a non-static method, it means that it is accessible with the class object only and if we try to access the object of another class it will give the error. It is a final method, cannot be overridden.

The ordinal() method returns the ordinal of the enum constant. (its position in its enum declaration, where the first constant is assigned an ordinal of zero).

Syntax: 

public final int ordinal();

Return Value:

This method returns the ordinal of this enumeration constant.

Example:

Day d1 = Day.TUESDAY;
System.out.println("the ordinal value is :" + d1.ordinal());

Output:
the ordinal value is : 2

Output
0 1 2 3 4 5 6 

compareTo() Method

The compareTo() method of Enum class compares this enum object with the defined object for order. Enum constants can only be compared to other enum constants of the same type.

Returns:

  1. A negative integer, if this enum is less than the defined object.
  2. zero, if this enum is equal to the defined object.
  3. a positive integer, if this enum is greater than the defined object.

Syntax:

int compareTo(Object obj)

Example:

Day day1 = Day.SUNDAY;

Day day2 = Day.MONDAY;

System.out.println(day1.compareTo(day2));

Since the ordinal value of day1 is less than day2 so it will return a negative value.


Output
-1
1
0

Ordinal() Method

CompareTo() Method

Returns the position of the enum constant
  • Returns A negative integer, if this enum is less than the defined object.
  • Returns zero, if this enum is equal to the defined object.
  • Returns a positive integer, if this enum is greater than the defined object.
It doesn't take any argument. It takes an enum constant as an argument.

Example: 

enum Day{

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;

}

Day d = Day.SUNDAY;

d.ordinal() // 0

Example:

enum Day{

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;

}

Day d1 = Day.SUNDAY;

Day d2 = Day.MONDAY;

d1.compareTo(d2) // since d1 < d2 output will be -ve

Comment
Article Tags: