Java String Equals
# Java String equals() Method
[Java String Class](#)
* * *
The equals() method is used to compare a string with a specified object.
The String class overrides the equals() method to compare the content of two strings for equality.
### 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("tutorial");
String Str2 = Str1;
String Str3 =new String("tutorial");
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 = trueReturn value = true
Comparing strings using == and equals().
In String, == compares whether the reference addresses are the same, while equals() compares whether the content of the strings is 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, 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](#)
YouTip