I always see this in lots of code:
String s;
if (s == null || s.isEmpty()) {
//do something
}
but isn't just enough
String s;
if (s.isEmpty()) {
//do something
}
I am curious especially when I check JavaFX TextField emptiness.
I always see this in lots of code:
String s;
if (s == null || s.isEmpty()) {
//do something
}
but isn't just enough
String s;
if (s.isEmpty()) {
//do something
}
I am curious especially when I check JavaFX TextField emptiness.
In general,
s.isEmpty()
checks if s
is an empty string, i.e. a string with no characters in it. If s
is null, attempting to call s.isEmpty()
(or attempting to call any other method on s
) will throw a null pointer exception.
(Note that it doesn't really make sense to ask "Does the isEmpty()
method check for null values": there's no way that s.isEmpty()
can possibly check if s
is null: the method cannot be invoked if s
is null.)
In the specific case you cite: checking a text field for emptiness, note that TextField.getText()
will not return null unless you explicitly set it to null first (with textField.setText(null)
). In other words the default value is an empty string, and the text property will not be set to null by "internal" methods invoked as the user types. Since your text field should be confined to the immediate class in which it is defined (or the controller for the FXML file in which it is created), you can control calls to its setText(...)
method and you can then guarantee that
TextField textField = ... ;
if (textField.getText() == null || textField.getText().isEmpty()) {
// ...
}
is equivalent to
TextField textField = ... ;
if (textField.getText().isEmpty()) {
// ...
}
by guaranteeing that textField.getText() == null
is always false.