Search code examples
javaoperator-keywordternary

Java Ternary Operator insert != null check and syso not printed


I have two questions. First

int i = 0;
System.out.println("\nint i is" + (i == 0) ? "i==0" : "i!=0");

I receive this error: Type mismatch: cannot convert from String to boolean
Eclipse tells me
1 quick fix available: Insert != null check

Second

System.out.println("\nint i is" + (i == 0) != null ? "i==0" : "i!=0");

With the != null check I get no error, but "\nint i is" is not printed, only the result i==0. I totally not understand the errors. Please help =)


Solution

  • You need to parenthesize your conditional expression properly:

    System.out.println("\nint i is" + ((i == 0) ? "i==0" : "i!=0"));
    

    Otherwise, + is executed before applying the conditional, so the conditional is parsed as follows:

    "\nint i is" + (i == 0) ? "i==0" : "i!=0"
    -----------------------   ------   ------
                 |              |         |
    Condition ---+              |         |
    When the condition is true -+         |
    When the condition is false ----------+
    

    "\nint i is" + (i == 0) is a valid Java expression that produces a string, triggering the "need a Boolean" error.