String.equals vs == operator in Java

To do the string equal check the (==) operator could be misleading because (==) tests for reference equality (whether they are the same object or not). On the other hand .equals() tests for value equality (whether they are logically “equal” or not).

In case of .equals()

// These two have the same value
new String("foo").equals("foo") // --> true 

In case of (==)

// ... but they are not the same object
new String("test") == "test" // --> false 
// ... neither are these
new String("test") == new String("test") // --> false 
Share