Home » Java programming language

Java Enum equals() method with example

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

Enum Class equals() method

  • equals() method is available in java.lang package.
  • equals() method is used to check equality or inequality of this Object against the given Object or in other words we can say this method is used to compare two objects.
  • equals() 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.
  • equals() method does not throw an exception at the time of comparing two Objects.

Syntax:

    public final boolean equals(Object obj2);

Parameter(s):

  • Object ob2 – represents the Object to compare with.

Return value:

The return type of this method is boolean, it returns the following values based on the given cases,

  • It returns true if Object1 is equal to Object2.
  • It returns false if Object1 is not equal to Object2.

Example:

// Java program to demonstrate the example 
// of boolean equals(Object obj2) method of 
// Enum class

enum Weeks {
    SUN,
    MON,
    TUE,
    WED,
    THU,
    FRI,
    SAT;
}
public class Equals {
    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;

        boolean res1 = w1.equals(w2);
        boolean res2 = w2.equals(w3);
        boolean res3 = w3.equals(w4);
        boolean res4 = w4.equals(w2);
        boolean res5 = w5.equals(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 false
Is MON same as TUE false
Is TUE same as WED false
Is WED same as MON false
Is THU same as FRI false



Comments and Discussions!

Load comments ↻






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