I've been taking a look at some GWT code written by various people and there are different ways of comparing strings. I'm curious if this is just a style choice, or if one is more optimized than another:
"".equals(myString);
myString.equals("");
myString.isEmpty();
Is there a difference?
The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.
The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The method returns 0 if the string is equal to the other string.
We can use == operators for reference comparison (address comparison) and . equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects.
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
"".equals(myString);
will not throw a NullPointerException
if myString
is null. That is why a lot of developers use this form.
myString.isEmpty();
is the best way if myString
is never null, because it explains what is going on. The compiler may optimize this or myString.equals("")
, so it is more of a style choice. isEmpty()
shows your intent better than equals("")
, so it is generally preferred.
Beware that isEmpty()
was added in Java 6, and, unfortunately, there are still people who complain pretty loudly if you don't support Java 1.4.
apache StringUtils provides some convenience methods for, well, String manipulation.
http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.CharSequence)
check out that method and associated ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With