alona
alona

Reputation: 33

Best method to check if a value of a String is null in Java

there are many implementation in how to check whether a String value is null and I'm really confused what to use!

These are my searches so far:

  1. if(myString == null){}

  2. Objects.equals(null, myString);

  3. ObjectUtils.isEmpty(myString)

  4. myString.equals(null)

  5. myString.compareTo(null);


NOTE: This is all about performance, reliable coding, fail-safe and other security purposes!

Updated: myString is dynamic, what if it was null, some of the implementation above will throw NullPointerException!

Upvotes: 1

Views: 18104

Answers (4)

oreokuchi
oreokuchi

Reputation: 11

`

String results;
if(results==null ||results.length()==0) {

}

`

Upvotes: -1

xingbin
xingbin

Reputation: 28279

  1. if(myString == null)

    Easiest and right way.

  2. Objects.equals(null, myString)

    A right way, its implemention is based on 1.

  3. ObjectUtils.isEmpty(myString)

    Not sure which ObjectUtils you are working with, but it seems to check myString is empty, not null.

  4. myString.equals(null)

    This does not work when myString is null, NPE will be thrown.

  5. myString.compareTo(null)

    This does not work when myString is null, NPE will be thrown.

Upvotes: 5

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

Another Option if you are using Java 8 you can use Optional::ofNullable

Optional.ofNullable(myString).isPresent()// true if not null, false if null

You can even use :

Optional.ofNullable(myString)
        .orElseThrow(() -> new Exception("If null throw an exception"));

There are many Options, just read the documentation


But as Mureinik mention in his answer == is enough in your case.

Upvotes: 8

Mureinik
Mureinik

Reputation: 311163

Just use a simple ==. There's no need to overcomplicate this.

Upvotes: 9

Related Questions