2.C] Write a note on:
i) ordinal()
ii) compareTo()
Answer:
In Java, both ordinal()
and compareTo()
methods are commonly used with enumerations (enum
) but can also be applied in other contexts. Here’s a detailed explanation of each:
i) ordinal()
- The
ordinal()
method returns the position of an enum constant in its enum declaration. The first constant is assigned an ordinal value of0
, the second1
, and so on. This method is useful when you need to know the order of constants within an enum. - Syntax:
enumName.constantName.ordinal()
- Example:
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public class OrdinalExample { public static void main(String[] args) { Day day = Day.WEDNESDAY; System.out.println("The ordinal of " + day + " is: " + day.ordinal()); } }
- Output:
The ordinal of WEDNESDAY is: 3
- In the example above,
WEDNESDAY
is the fourth constant in the enumDay
, so its ordinal value is3
.
ii) compareTo()
- The
compareTo()
method is used to compare the ordinal values of two enum constants. It returns: 0
if the two enum constants are the same.- A negative integer if the current enum constant’s ordinal is less than the compared enum constant’s ordinal.
- A positive integer if the current enum constant’s ordinal is greater than the compared enum constant’s ordinal.
- Syntax:
enumName.constantName1.compareTo(enumName.constantName2)
- Example:
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public class CompareToExample { public static void main(String[] args) { Day day1 = Day.MONDAY; Day day2 = Day.WEDNESDAY; int result = day1.compareTo(day2); if (result == 0) { System.out.println(day1 + " is equal to " + day2); } else if (result < 0) { System.out.println(day1 + " comes before " + day2); } else { System.out.println(day1 + " comes after " + day2); } } }
- Output:
MONDAY comes before WEDNESDAY
- In this example,
MONDAY
has an ordinal value of1
andWEDNESDAY
has an ordinal value of3
. Since1 < 3
, thecompareTo()
method returns a negative integer, indicating thatMONDAY
comes beforeWEDNESDAY
.
Summary:
ordinal()
provides the position of an enum constant within the enum declaration.compareTo()
compares the ordinal values of two enum constants to determine their order relative to each other.
These methods are particularly useful for managing and organizing enums in Java.