Java String equals() Method

A primary way for determining whether the contents of two objects are equal in Java is the equals() function. It is used particularly to compare the contents of two String objects in the context of the String.

Explanation

The String equals() function in Java compares two strings based on their data/content.

It returns true if all of the contents of both strings match. It returns false if none of the characters match.

How do use Strings equals() in Java:

  • On a String object, you invoke the equals() function and send it another Object (usually a String) as an argument.
  • If the content (character sequence) of the two String objects matches, it returns true; if not, it returns false.

Syntax:

public boolean equals(Object anotherObject)

Parameters:

anotherObject is described in the parameterAn object that represents the competing string for comparison

Return value:

A boolean indicates the outcome as

  • The strings are equal if it returns true.
  • The strings are not equal if it returns False

Example for Return Value:

public class Main {
  public static void main(String[] args) {
    String str1 = "Learn Java";
    String str2 = "Learn Java";

    // Comparing strings str1 and str2 (TechVidvan example)
    boolean result = str1.equals(str2);

    System.out.println(result);
  }
}

Output:
true

Example:

import java.lang.*;

public class TechVidvanEqual {
    public static void main(String[] args) {

        // Instantiate a String class
        String str = new String("Java");

        // Initialize the string object
        String obj = "Java";
        System.out.println("The given string is: " + str);
        System.out.println("The object is: " + obj);

        // Using the equals() method to compare strings (TechVidvan example)
        System.out.println("The given string is equal to the specified object or not? " + str.equals(obj));
    }
}

Output:
Java
Java
True

  • Equals(Object): Determines whether this instance and a specified object, which must also be a String object, have the same value.
  • Equals(String): Determines whether this instance and another specified String object have the same value.
  • Equals(String, String): Determines whether two specified String objects have the same value.

Difference between equals() vs equalsIgnoreCase() in Java:

Check whether a pair of strings are equal by using the equals() function in Java. In Java, to check for an equal representation of two strings that ignore a case, use equalsIgnoreCase().

So, let me give you two strings

String one =”qwerty”;
String two = “Qwerty”;

The two of them are identical, but the case is different. When the method excludes a case, it would consider both of these strings to be equivalent by means of equalsIgnoreCase().

Example:

public class TechVidvan{
         public static void main(String[] args) {

       String one = "qwerty";
       String two = "Qwerty";
       if (one.equalsIgnoreCase(two)) {
    System.out.println("String 'one' is equal to 'two' ");
        }
else {
    System.out.println("String 'one' is not equal to 'two'");
         }

if (one.equals(two)) {
    System.out.println("String 'one' is equal to 'two' ");
        }
else {
    System.out.println("String 'one' is not equal to 'two' ");
        }
    }
}

string equals

Use of String equals():

public class
TechVidvan EqualsExample {  
    public static void main(String[] args)
{  
     String s1 = "TechVidvan";  
     String s2 = "TechVidvan";  
     String s3 = "TECHVIDVAN";  
     String s4 = "Java";  
     System.out.println(s1.equals(s2)); // true because content and case are the same  
     System.out.println(s1.equals(s3)); // false because case is not the same  
     System.out.println(s1.equals(s4)); // false because content is not the same  
    
}

Output:
True
False
False

Exception for Java Strings equals():

  • Java’s equals() function will return false when called on a null reference rather than throwing an exception.
  • The way Java handles method calls on null references for non-static methods is consistent with this practice.

Advantages of Java Strings equals():

  • Comparison of Content: The main benefit of using equals() is the ability to contrast the content (a sequence of characters) of two String objects. This is crucial if you wish to compare two strings of textual data to see if they reflect the same data.
  • Custom Comparison: You can design your own logic for comparing objects based on their characteristics by overriding the equals() function for custom classes. This enables you to perform unique equality checks catered to the needs of your application.

Technical details:

  • Handling Nulls:Calling equals() on a string that might be null is secure. The function will return false if the invoking string is empty.
  • String Object vs. String Literal : It can be applied to both string literal and string object comparisons.Since string literal comparisons are based on content, two identical string literals will have the same result.
  • Overriding:In user-defined classes, the equals() method is frequently changed to implement unique comparison logic.

Disadvantage of Strings equals() in Java:

  • Null Safety: If you try to use equals() on a null reference, it will return false rather than throwing an exception. If you neglect to explicitly handle null references, this behavior may produce unanticipated outcomes.
  • Case Sensitivity: While case sensitivity can be beneficial, there are times when case-insensitive comparisons are required. You would need to convert strings to lowercase or uppercase before comparison.

Conclusion

We have extensively discussed the equals() function in Java. We briefly discussed the use of the equals() method and then moved on to see how using this method can help reduce a significant amount of code in a program.