Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java String equals() Method

Java String equals() Method

Java String ClassJava String class


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

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

Syntax


public boolean equals(Object anObject)

Parameters

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

(

"runoob"

)

;

       

String

Str2

=

Str1

;

       

String

Str3

=

new

String

(

"runoob"

)

;

       

boolean

retVal

;

        retVal

=

Str1.

equals

(

Str2

)

;

       

System

.

out

.

println

(

"Return value = "

retVal

)

;

        retVal

=

Str1.

equals

(

Str3

)

;

       

System

.

out

.

println

(

"Return value = "

retVal

)

;

   

}

}

The execution result of the above program is:


返回值 = true
返回值 = true

Comparing strings using == and equals().

In String, == compares whether the reference addresses are the same, while equals() compares whether the string contents 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 common pool with the 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 ClassJava String class