javanullpointerexceptionconditional-operatorboxingautoboxing

Why does this code give a null pointer Exception? I thought Character class could handle null being assigned?


public class Playground {
  public static void main(String[] args) {
    String s = "blah";
    Character lclfs = s.contains("/") ? '/' : s.contains("\\") ? '\\' : null;
  }
}

What am I missing (using Java 1.8)?

enter image description here


Solution

  • That is because your code will try to unbox null. Using IntelliJ this will be shown directly as warning: "Unboxing of null may produce NullPointerException".

    An alternative would be to do it like this:

    String s = "blah";
    Character lclfs = s.contains("/") ? Character.valueOf('/') : 
        s.contains("\\") ? Character.valueOf('\\') : null;
    

    As @Antoniossss pointed out, this would also help:

    String s = "blah";
    Character lclfs = s.contains("/") ? Character.valueOf('/') : 
        s.contains("\\") ? (Character)'\\' : null;
    

    Talking about warnings in IntelliJ, my above code is now saying: ”Unnecessary boxing 'Character.valueOf('\')'”. So probably you should try to refactor your code. Instead of using explicit null, you could introduce java.util.Optional:

    Optional<Character> lclfs = s.contains("/") ? Optional.of('/') :
            s.contains("\\") ? Optional.of('\\') : Optional.empty();