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.
I think
isEmpty()is a bit more efficient. However a smart compiler may optimize theequals("")call anyway. From the OpenJDK source:Also the answer here on whether to use
str.isEmpty()or"".equals(str)is spot on: