mastaH mastaH - 18 days ago 4
Java Question

Difference between String.isEmpty() and String.equals("")

I created a "Color Chooser" with three textboxes where the user defines rgb values.

To check if values entered are correct (only numbers between 0-255) I'm using the following:

public Color getColor() {
if (tfRed.getText().equals("") || tfGreen.getText().equals("") || tfBlue.getText().equals("")) {
return new Color(0, 0, 0, 0);
} else {
if (tfRed.getText().matches("\\d+") && tfGreen.getText().matches("\\d+") && tfBlue.getText().matches("\\d+")) {
// ...
} else {
return new Color(0, 0, 0, 0);
}
}
}


What I'm asking: is it better to use
String.isEmpty()
? I never found a satisfying answer and I've always wondered if there is any difference.

Answer

I think isEmpty() is a bit more efficient. However a smart compiler may optimize the equals("") call anyway. From the OpenJDK source:

  671     public boolean isEmpty() {
  672         return count == 0;
  673     }

 1013     public boolean equals(Object anObject) {
 1014         if (this == anObject) {
 1015             return true;
 1016         }
 1017         if (anObject instanceof String) {
 1018             String anotherString = (String)anObject;
 1019             int n = count;
 1020             if (n == anotherString.count) {
 1021                 char v1[] = value;
 1022                 char v2[] = anotherString.value;
 1023                 int i = offset;
 1024                 int j = anotherString.offset;
 1025                 while (n-- != 0) {
 1026                     if (v1[i++] != v2[j++])
 1027                         return false;
 1028                 }
 1029                 return true;
 1030             }
 1031         }
 1032         return false;
 1033     }

Also the answer here on whether to use str.isEmpty() or "".equals(str) is spot on:

The main benefit of "".equals(s) is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you're checking, you care whether or not s is empty, not whether it equals the empty string