Java String equals() Method

Java String类Java String Class


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

The equals() method is overridden in the String class to compare whether the contents of two strings are equal.

Syntax

public boolean equals(Object anObject)

Parameters

  • anObject-- The object to compare with the string.

Return Value

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

Example

Example

public class Test {
    public static void main(String args[]) {
        String Str1 = new String("example");
        String Str2 = Str1;
        String Str3 = new String("example");
        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:

返回值 = true
返回值 = true

Use==andequals()Compare strings.

In String,==== compares whether the reference addresses are the same,equals()equals compares whether the contents of the strings are the same:

String s1 = "Hello";              // String created directly
String s2 = "Hello";              // String created directly
String s3 = s1;                   // Same reference
String s4 = new String("Hello");  // String object created
String s5 = new String("Hello");  // String object created
 
s1 == s1;         // true, same reference
s1 == s2;         // true, s1 and s2 are both in the public 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类Java String Class

Other Extensions