Home » Java programming language

Java Enum compareTo() method with example

Enum Class compareTo() method: Here, we are going to learn about the compareTo() method of Enum Class with its syntax and example.
Submitted by Preeti Jain, on December 06, 2019

Enum Class compareTo() method

  • compareTo() method is available in java.lang package.
  • compareTo() method is used to check equality or inequality for this Enum object against the given Enum object mathematically or in other words, we can say this method is used to compare two Enum constants of the same type.
  • compareTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • compareTo() method is a final method so, it is not overridable in child class.
  • compareTo() method does not throw an exception at the time of comparing the Enum object.
    NullPointerException: When the specified argument is null.

Syntax:

    public final int compareTo(Enum obj2);

Parameter(s):

  • Enum obj2 – represents the Enum object to compare with.

Return value:

The return type of this method is int, it returns an integer value based on the given cases,

  • It returns 0 when this Enum object is equal to or same as the given Enum object.
  • It returns positive value when this Enum object is greater than the given Enum object.
  • It returns negative value when this Enum object is less than the given Enum object.

Example:

// Java program to demonstrate the example 
// of int compareTo(Enum obj2) method of 
// Enum class

enum Weeks {

    SUN,
    MON,
    TUE,
    WED,
    THU,
    FRI,
    SAT;
}
public class CompareTo {
    public static void main(String args[]) {

        Weeks w1 = Weeks.SUN;
        Weeks w2 = Weeks.MON;
        Weeks w3 = Weeks.TUE;
        Weeks w4 = Weeks.WED;
        Weeks w5 = Weeks.THU;
        Weeks w6 = Weeks.FRI;
        Weeks w7 = Weeks.SAT;

        int res1 = w1.compareTo(w2);
        int res2 = w2.compareTo(w3);
        int res3 = w3.compareTo(w4);
        int res4 = w4.compareTo(w2);
        int res5 = w5.compareTo(w6);

        System.out.println("Is" + " " + w1.name() + " " + "same as" + " " + w2.name() + res1);
        System.out.println("Is" + " " + w2.name() + " " + "same as" + " " + w3.name() + res2);
        System.out.println("Is" + " " + w3.name() + " " + "same as" + " " + w4.name() + res3);
        System.out.println("Is" + " " + w4.name() + " " + "same as" + " " + w2.name() + res4);
        System.out.println("Is" + " " + w5.name() + " " + "same as" + " " + w6.name() + res5);
    }

}

Output

Is SUN same as MON-1
Is MON same as TUE-1
Is TUE same as WED-1
Is WED same as MON2
Is THU same as FRI-1


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.