Compare Strings in Java: Java String equals() Method Tutorial

In this section, we will learn what the String equals() method is and how to use it in Java to compare string values.

How to Compare Strings in Java? And What is Java String equals() Method?

The `equals()` method compares two string objects to see if they are equal in CONTENT or not.

Basically, this method doesn’t care if both String objects are two independent objects! All that is a matter for this method is the content of the string values!

Java equals() Method Syntax:

public boolean equals(Object anotherObject)

equals() Method Parameters:

This method takes one argument and that is the string value we want to compare with the string value that the method is invoked with.

Note: the `equals()` method is case sensitive. For example, a value like `Hello` is different from the word `HELLO` or `hELLO`.

equals() Method Return Value:

The return value of this method is a Boolean.

If the string values are the same, the result will be true, otherwise it is false.

Example: using String equals() method

public class Simple {

    public static void main(String[] args) {
        String s1 = new String("Hello to all people out there");

        System.out.println(s1.equals("Hello to all people"));
        System.out.println(s1.equals("Hello to all people out there"));
    }
}
Output: 
false 
true

Difference between == and .equals() method in Java

The equal `==` operator is used to check if two involved operands are pointing to the same object in the heap memory!

But as mentioned before, the use of equals() method is mainly for checking and see if two string values are equal in characters.

Leave a Reply