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

10,888

Solution 1

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

Solution 2

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.

Solution 3

  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.

Share:
10,888

Related videos on Youtube

alona
Author by

alona

Updated on June 04, 2022

Comments

  • alona
    alona almost 2 years

    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!

  • alona
    alona about 6 years
    sorry if my question was not clear, but I was having NPE when comparing it when myString is null, I have updated my question. Thanks! i guess == is not fail safe
  • C.Champagne
    C.Champagne about 6 years
    @djrumix123 == IS fail safe in this case because you don't access any member of a potentially null string. string1.equals(string2) is not: It will throw a NPE if string1 is null. The problem with == is that it compares references, so it is valid to determine if a string is null or not but it is not pertinent to compare if two string have the same value.
  • Mureinik
    Mureinik about 6 years
    @djrumix123 as C.Champagne said - checking myString != null is the safest approach, and probably the best performing one too (you're just checking the reference's identity).
  • Youcef Laidani
    Youcef Laidani about 6 years
    @djrumix123 the new features also can help you a lot ;)
  • alona
    alona about 6 years
    i'll try this though!
  • Hoppeduppeanut
    Hoppeduppeanut about 5 years
    This will not compile, as results is uninitialized. Even if it worked, results==null would cover the OP's requirements, which have already been covered in previous answers.