Difference Between Java Operator == and equals() Method
Comparing Strings
In Java, == and equals() are used when comparing strings, but they have different meanings.
== is a comparison operator that compares address values, while the equals() method compares the content itself, that is, the data value.
Therefore, they should be used differently depending on the situation.
package com.devkuma.basic.string;
public class StringEquals {
public static void main(String[] args) {
String a = "devkuma";
String b = "devkuma";
String c = new String("devkuma");
String d = new String("devkuma");
System.out.println(a == b); // true
System.out.println(b == c); // false
System.out.println(c == d); // false
System.out.println(a.equals(b)); // true
System.out.println(b.equals(c)); // true
System.out.println(c.equals(d)); // true
}
}
Execution result:
true
false
false
true
true
true
The detailed explanation of the result values is as follows.
| Expression | Result | Description |
|---|---|---|
a == b |
true |
Because of the string constant pool, the same address value is assigned to a and b, so the comparison result is true. |
b == c |
false |
b is assigned an address value from the string constant pool, while c is assigned a new address value by the new operator, so the comparison result is false. |
c == d |
false |
c is assigned a new address value by the new operator, and d is also assigned a new address value by the new operator, so the comparison result is false. |
a.equals(b) |
true |
Only the values of a and b are compared, so the result is true. |
b.equals(c) |
true |
Only the values of b and c are compared, so the result is true. |
c.equals(d) |
true |
Only the values of c and d are compared, so the result is true. |