equals() method in java with Simple Examples

Explanation: What is equals method in java

The equals is method use for comparing two object and return boolean value true or false based on comparison. You can also override this method.

When it comes to string comparison java automatically override equals method to compare that string based on their data type and value.

Syntax:

public boolean equals(Object anotherObject)  

parameter:

anotherObject - Any Object

Returns:boolean value:

true - if the strings are equal
false - if the strings are not equal

equals method in java object class

The equals method in java is used to compares the calling object with another object and return true if they are equal otherwise return false.

When we used equals method for object comparison then it will compare data type, value and location.

class DemoExample{
    public static void main( String args[] ) {
        ( object__one ).equals( object__two )
    }
}

You can typically override this method.

equals() method in java example

Example1:

public class StringEqualsExample{  
public static void main(String args[]){  
String s1="kekmart";  
String s2="kekmart";  
String s3="KEKMART";  
String s4="programiz";  
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));  
System.out.println(s1.equals(s4));  
}}  

Example2:

public class Example { 

   public static void main(String args[]) {
      Integer x = 5;
      Integer y = 10;
      Integer z =5;
      Short a = 5;

      System.out.println(x.equals(y));  
      System.out.println(x.equals(z)); 
      System.out.println(x.equals(a));
   }
}

equals method in java string

class StringEquals {
    public static void main( String args[] ) {
        String str1 = "hello";
        String str2 = "Hello";
        String str3 = "hello";

        System.out.print(str1.equals(str2) + "\n");

        System.out.print(str1.equals(str3));
    }
}

equals method in java for integer

class NumberEquals {
    public static void main( String args[] ) {
        Integer number1 = 5;
        Integer number2= 6;
        Integer number3= 5;

        System.out.print(number1.equals(number2) + "\n");
        System.out.print(number1.equals(number3));
    }
}

equals method in java for character

class CahrEquals {
    public static void main( String args[] ) {
        String char_one = "c";
        String char_two = "d";
        String char_three = "c";

        System.out.print(char_one.equals(char_two) + "\n");

        System.out.print(char_one.equals(char_three));
    }
}

equals method in java for boolean

class BoolEquals {
    public static void main( String args[] ) {
        Boolean bool_1 = true;
        Boolean bool_2 = false;

        System.out.print(bool_1.equals(bool_2) + "\n");
        System.out.print(bool_1.equals(bool_1));
    }
}

Was this article helpful?
YesNo

Leave a Comment