Why does this code give a null pointer Exception? I thought Character class could handle null being assigned? [duplicate]
Asked Answered
M

1

-1
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

Mayonnaise answered 13/10, 2021 at 8:19 Comment(2)
Wow it does, I would say its because of autounboxing attemptJuieta
Not sure if it was the same and worth closing - they are similar -this was Character class. Definitely worth cross linking posts though. Cheers for all the help from everyone on this one. Was a real Java curveball for me!Mayonnaise
W
1

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();
Writ answered 13/10, 2021 at 8:25 Comment(3)
I wonder why it is unboxed to char?Juieta
Thank you very much. That solved it. I thought Java would auto box. Very quirky! ;-)Mayonnaise
Also, casting is enoughJuieta

© 2022 - 2024 — McMap. All rights reserved.