eeijlar eeijlar - 11 months ago 34
Java Question

How do I use if/else shortcut to print string based on boolean value

I would like to print:

Permissive mode: ON


Permissive mode: OFF

I was trying to do it in one line like this:

logMessage("Permissive mode: " + (isPermissive == true) ? "ON" : "OFF" );

I could do full if/else statement and a separate variable for ON/OFF but was trying to keep it short...


You need parentheses around the conditional assignment operator ? : because there's an addition operator before it, and + has a higher precedence than ? :.

Without the parentheses, "Permissive mode: " + (isPermissive == true) ? "ON" : "OFF"

is equivalent to ("Permissive mode: " + (isPermissive == true)) ? "ON" : "OFF"

The result of the + addition operator with String operands isn't a boolean, so the compiler will complain rightfully on the expression.

You need to surround the operator with less precedence with parentheses if you want it to evaluate first:

logMessage("Permissive mode: " +  (isPermissive ? "ON" : "OFF") );