Home >Java >javaTutorial >Java String Comparison: `==` vs. `.equals()` – When to Use Which?
Object Reference Comparison vs. Value Equality in Java
In Java, determining object equality can be confusing when comparing strings using the == operator. Let's delve into this seemingly ambiguous behavior.
Consider the following scenario:
// Define a String array String[] parts = {"231", "CA-California", "Sacramento-155328", "aleee", "Customer Service Clerk", "Alegra Keith.doc.txt"}; // Perform comparison if ("231" == parts[0]) { // This comparison will evaluate to false }
Surprisingly, the comparison returns false. This is because the == operator in Java checks for object reference equality, not value equality. Unlike in many other languages, Java strings are objects. When you compare two strings using ==, it compares the memory addresses where those objects reside, not the actual string values.
To compare the actual values of strings, you should use the String.equals method:
if ("231".equals(parts[0])) { // This comparison will evaluate to true }
This method checks the content of the strings, not their object references.
Remember, for all objects in Java, the == operator checks reference equality, while the equals method compares the actual object values. It's important to use equals when checking for equality of objects, as == can lead to incorrect conclusions when comparing object references.
The above is the detailed content of Java String Comparison: `==` vs. `.equals()` – When to Use Which?. For more information, please follow other related articles on the PHP Chinese website!