Difference in STRING.equals(“foo”) vs STRING == “foo”
- By bkuhl
- 11 April, 2012
- No Comments
I’ve been working on learning java and today I was performing a string comparison shown below when my IDE showed a little light bulb icon with a “!” on it.
if (request.getMethod() == "POST" && !search.isEmpty()) {
}
Netbeans doesn’t like this comparison. It doesn’t like it because while it is my intention to compare the output value of getMethod() against “POST”, the “==” operator won’t do that. The “==” operator compares the actual objects to see if they both reference the same object.
String x = new String("foo");
String y = new String("foo");
String copyOfX = x;
System.out.println(x == y); // false
System.out.println(x.equals(y)); // true
System.out.println(x == copyOfX); // true
In the above example you’ll see that x == copyOfX returns true. This is because both objects are in fact, the same object. While the x and y string values are the same, they are not the same string object.
When comparing string values, always use .equals()
Copyright © 2013