0

If I wish to perform two checks on a string, that it is not null, and that it is not 0 length, I could do this-

if(string != null) {
    if(string.length() > 0) {
        //Do something
    }
}

Or I could do this

if(string != null && string.length() > 0) {
    //Do something
}

As the first check is executed first, the second comparison doesn't happen and a NullPointerException isn't thrown.

Is the second method guaranteed to work in all cases? And if so, would it be considered bad practice to use it?

Theo Pearson-Bray
  • 775
  • 1
  • 13
  • 32
  • 1
    Order of operations is well defined in Java, so that's perfectly safe. It's also a pretty common way to do it. – resueman Aug 25 '16 at 17:24
  • 1
    Using the `&&`, if the first check fails, the second is not evaluated. Also known as short-circuting. So it will not produce a `NullPointerException` – Orin Aug 25 '16 at 17:24
  • Ok, thanks. That is what I assumed, however I didn't know if was guaranteed to always happen. – Theo Pearson-Bray Aug 25 '16 at 17:26
  • [Java, check whether a string is not null and not empty?](http://stackoverflow.com/q/3598770) – Tom Aug 25 '16 at 17:28

3 Answers3

5

No, it is perfectly fine and guaranteed to work in all cases.

Reference from Java specification: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.7

uoyilmaz
  • 3,035
  • 14
  • 25
1

The one worth mentioning here: as you write such checks very often, it is advisable to put them into some dedicated helper method; such as:

static boolean doesStringContentContent(String value) {

or something alike.

And from an "improved" readability perspective, you might prefer coding that like

if (value == null) return false;
if (value.isEmpty()) return false;
return true;

But that doesn't matter too much - the important part is that you should not start copying around this check.

And finally, the one other possibility would to not return a boolean, but to have a

void checkStringHasContent(String value) {

which could throw a NullPointerException resp. some other thingy for an empty string.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

you are using && (and) operator in second expression. and nested if condition in first expression. in both cases you will get same result. because &&(and) operator execute second condition if only if first condition is true.

basically you are doing same thing in different manner.

Abhishek
  • 379
  • 1
  • 8