Open In App

String equals() Method in Java

The equals() method of the String class compares the content of two strings. It returns false if any of the characters are not matched. It returns true if all characters are matched in the Strings. It compares the value’s character by character, irrespective of whether two strings are stored in the same memory location. The String equals() method overrides the equals() method of the object class.

Syntax:

string.equals(object)

Return Type: The return type for the equals method is Boolean.



Examples of String equals() Method in Java

Below is the code implementation of the usage of the String equals() method in Java.

Example 1: Basic Comparision




// Java program to demonstrate String equals() method
import java.io.*;
class Main 
{
  public static void main(String[] args) 
  {
    String str1 = "Learn Java";
    String str2 = "Learn Java";
    String str3 = "Learn Kotlin";
    boolean result;
  
    // comparing str1 with str2
    result = str1.equals(str2);
    System.out.println(result);   
  
    // comparing str1 with str3
    result = str1.equals(str3);
  
    System.out.println(result); 
  
    // comparing str3 with str1
    result = str3.equals(str1);
    System.out.println(result);  
  }
}

Output

true
false
false


Explanation of the above Program:

In the above program,

Example 2: Case-Insensitive Comparison

It compares the difference between uppercase and lowercase characters.




import java.io.*;
  
public class CaseInsensitiveComparisonExample 
{
    public static void main(String[] args) 
    {
        // define three strings
        String str1 = "Hello";
        String str2 = "hello";
        String str3 = "WORLD";
  
  
        // comparison between str1 and str2
        System.out.println("str1.equals(str2): " + str1.equals(str2)); 
  
        // comparison between str1 and str2
        System.out.println("str1.equalsIgnoreCase(str2): " + str1.equalsIgnoreCase(str2)); 
  
        // comparison between str2 and str3
        System.out.println("str2.equalsIgnoreCase(str3): " + str2.equalsIgnoreCase(str3)); 
    }
}

Output
str1.equals(str2): false
str1.equalsIgnoreCase(str2): true
str2.equalsIgnoreCase(str3): false


Explanation of the above Program:

In the above program,


Article Tags :