InvalidTypeException when trying to initialize an Integer variable with ternary operator

Viewed 33

Can someone enlighten what is the explanation behind this? Why is an exception thrown?

package integerProblem;

public class Test {
    
    public enum Letter{
        A, B, C;
    }
    
    public static void main(String[] args) {
        Letter foo = Letter.C;
        
        Integer bar = Letter.A == foo ? 1 : null; // bar is set to null.
        System.out.println("Value of bar: " + bar);
        
        Integer baz = Letter.A == foo ? 1 : Letter.B == foo ? -1 : null; // com.sun.jdi.InvalidTypeException: Generated value (null) is not compatible with declared type (int). occured invoking method.
        System.out.println("Value of bar: " + baz);
    }

}

Output:

Value of bar: null
Exception in thread "main" java.lang.NullPointerException
    at integerProblem.Test.main(Test.java:15)

1 Answers

If bar or baz are null they can't be joined with a String, only a valid object can be used with another String and + (it will implicitly call toString() on the object). You may wish to consider using an empty String ("") instead, that should work.

Related