-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

JGFMK
  • 8,425
  • 4
  • 58
  • 92
  • 1
    Wow it does, I would say its because of autounboxing attempt – Antoniossss Oct 13 '21 at 08:25
  • 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! – JGFMK Oct 13 '21 at 08:32

1 Answers1

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();
jmizv
  • 1,172
  • 2
  • 11
  • 28