简体   繁体   中英

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!

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

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.

  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.

`

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

}

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM