-1

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.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
DeluxeD
  • 133
  • 1
  • 5
  • 19
  • 3
    If `s` does not reference an instance, you can't call an instance method on it. [*The variable `s` is not an object.*](http://stackoverflow.com/documentation/java/4388/common-java-pitfalls/24130/) – Andy Thomas May 15 '17 at 19:03
  • Calling `isEmpty()` without previously checking for `null` can cause `NullPointerException`. – Pavlo Viazovskyy May 15 '17 at 19:03
  • You should probably check JavaFx TextFields by textfield.getText().length(). It will eliminate having to check for null. If the lengh == 0, the textfield has no visible text. – SedJ601 May 15 '17 at 19:31

1 Answers1

3

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.

James_D
  • 201,275
  • 16
  • 291
  • 322