String equals() vs == in Java

In this tutorial, we will learn about String equals() vs == in Java.

Two Strings in Java can be compared using equals() and == operator in Java. equals() and == are used to compare Strings, there is a difference between the operations between these two. The equals( ) method compares the characters inside a String object. == operator compares two object references to see whether they refer
to the same instance.
The equals() method compares the value inside String instances irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance, then it is fine. If the two object references refer to two different String instances, then also it doesn’t make a difference. It’s the value inside each String instance that is being compared.

1) String comparison using equals() method:

String class provides two methods equals() and equalsIgnoreCase().

public boolean equals(Object obj) – compares this string to the specified object.
public boolean equalsIgnoreCase(String another) – compares this String to another string, ignoring case.



2) String comparison using == operator:

The = = operator compares references not values.