Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String Comparison: style choice or optimization?

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?

like image 401
KevMo Avatar asked Jul 13 '10 21:07

KevMo


People also ask

What is the best way to compare strings in Java?

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.

Which method do we use for string comparison?

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.

Why use .equals instead of == Java?

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.

What are the 3 ways to compare two string objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.


3 Answers

"".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.

like image 106
Aaron Avatar answered Oct 11 '22 09:10

Aaron


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.

like image 33
erickson Avatar answered Oct 11 '22 09:10

erickson


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.

like image 27
hvgotcodes Avatar answered Oct 11 '22 08:10

hvgotcodes