Easy Tutorial
❮ Net Urldate Java Hashmap Values ❯

Java String equals() Method

Java String Class


The equals() method is used to compare the string with the specified object.

The equals() method in the String class is overridden to compare the contents of two strings for equality.

Syntax

public boolean equals(Object anObject)

Parameters

Return Value

Returns true if the given object is equal to the string; otherwise, returns false.

Example

public class Test {
    public static void main(String args[]) {
        String Str1 = new String("tutorialpro");
        String Str2 = Str1;
        String Str3 = new String("tutorialpro");
        boolean retVal;

        retVal = Str1.equals(Str2);
        System.out.println("Return Value = " + retVal);

        retVal = Str1.equals(Str3);
        System.out.println("Return Value = " + retVal);
    }
}

The output of the above program is:

Return Value = true
Return Value = true

Comparing strings using == and equals().

In String, == compares the reference addresses, while equals() compares the contents of the strings:

String s1 = "Hello";              // Directly created String
String s2 = "Hello";              // Directly created String
String s3 = s1;                   // Same reference
String s4 = new String("Hello");  // Object created String
String s5 = new String("Hello");  // Object created String

s1 == s1;         // true, same reference
s1 == s2;         // true, s1 and s2 are in the common pool, same reference
s1 == s3;         // true, s3 has the same reference as s1
s1 == s4;         // false, different reference addresses
s4 == s5;         // false, different reference addresses in the heap

s1.equals(s3);    // true, same content
s1.equals(s4);    // true, same content
s4.equals(s5);    // true, same content

Java String Class

❮ Net Urldate Java Hashmap Values ❯