In Java, comparing Strings using ==
operator checks if the references of the String objects are the same, not the actual content of the Strings.
To compare the content of Strings, you should use the .equals()
method. Let's see an example to clarify the difference:
String inStr = "heartbeat";
String heartbeat = "heartbeat";
if (inStr == heartbeat) {
System.out.println("Strings are equal using ==");
}
if (inStr.equals(heartbeat)) {
System.out.println("Strings are equal using .equals()");
}
The output of this code will be:
Strings are equal using =
Strings are equal using .equals()
In this example, the ==
operator returns true because both inStr
and heartbeat
references the same String object in memory. On the other hand, .equals()
method returns true because they both have the same content.
Therefore, to check if two Strings are equal in Java, always use the .equals()
method. The ==
operator should only be used when comparing references, not the content of objects.