ZMedia Purwodadi

Java String equals() method explained | technical-arbaab

Table of Contents

Java String equals() method explained


It is a predefined function which is present in the Java.lang.String package. It is used to compare two strings and return boolean type true if the strings are equal and false if the strings are unequal let's see this in the code directly-

Syntax of equals() method

 public boolean equals(Object anObject) {}  

here, the Object inside the parameter, represents another string to be compared simply.

Example 01 of equals() method

 public class Equals {  
      public static void main(String[] args)  
      {  
           String s1 = "hello";  
           String s2 = "bello";  
           System.out.println(s1.equals(s2));   
      }  
 }  

Output:

 false  

here, the strings "hello" and "bello" are not equal so it has returned false checkout the compareTo() method to compare two strings lexicographically.

Imp.note: here, the string class overrides the equals method present inside the Object class.

Why to use equals() instead of (==) to compare two strings

Because by comparing two strings using (==) the reference to the object is actually checked for example here the string object s1 points to the string "hello" inside the string constant pool and the string object s2 points to the string "bello" inside the string constant pool so it will also print false because both the object refer to the different strings and we use equals() method to compare the content of the string.

Example of compare strings using (==) operator

 public class Equals {  
      public static void main(String[] args)  
      {  
           String s1 = "hello";  
           String s2 = "hello";  
           System.out.println(s1==s2);//also prints false  
           //because both objects refer to the different strings   
           //inside the string constant pool  
           String s3 = "jack";  
           String s4 = "jack";  
           System.out.println(s3==s4);  
           //it will prints true because both the objects  
           //refer to the same string inside the string   
           //constant pool  
      }  
 }  

output

 true  
 true  

To know more about various operators in Java refer to operators in Java.

Arbaab khan
Arbaab khan FEAR has two meanings "forget everything and run" "Face everything and rise" The choice is yours Welcome u in our tech blog

إرسال تعليق