Chandra's Tech Blog

== Versus .equals() in Java

Frequently in Java code we come across the usage of == and equals(). The question arises whether == and equals() perform the same operations or whether they work differently. To answer this question, let us examine how == and equals() work and then identify their differences.

The == operator:

The == is a relational operator in Java that is used to compare two operands. It is used to determine whether the two operands are equal or not. Using the == operator, you can compare any primitive type such as int, char, float and Booleans. After comparison, the == operator returns a boolean value. If the two operands are equal, the == operator returns a true value. However, if the two operands are not equal, it returns a false value.
When used with objects, the == operator compares the two object references and determines whether they refer to the same instance.

The .equals() Method

equals() is a method available in the String class that is used to compare two strings and determine whether they are equal. This method returns a boolean value as a result of the comparison. If the two strings contain the same characters in the same order, the equals() method returns true. Otherwise, it returns a false value.

== Versus .equals()

Though the == operator and the equals() method are used to test equality, they do not work the same way. While the equals() method compares each character within the two String objects, the == operator compares the two object references. Let’s consider the following example.

Here, str1 refers to a String instance that contains “Good Day” and str2 refers to a new object created using str1 as the initializer. Though the two String objects str1 and str2 contain the same content “Good Day”, they are two different objects. Therefore, str1 and str2 refer to different instances and the == operator returns a false value as the result.

Hi
Folks,
you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,