How to print a statement (not a char) using Ternary Conditional


#1

The exercise tells you how to print the character. But what if I want to print a statement using this shortcut for if/else?


#2

System.out.println(2 > 3 ? "Condition is true" : "Condition is false");

#3

Thanks factoradic. Just so i know, the code written in exercise is
char canDrive = (fuelLevel>0) ? 'Y' : 'N';
So going by your line, shouldn't the position of parenthesis be
System.out.println (2 > 3) ? "Condition is true" : "Condition is false";


#4

Nope. This code:

char canDrive = (fuelLevel>0) ? 'Y' : 'N';

is exactly the same as:

char canDrive = fuelLevel>0 ? 'Y' : 'N';

Parentheses in the first snippet are there only to mark where the condition starts and ends. You can add them to our println statement:

System.out.println((2 > 3) ? "Condition is true" : "Condition is false");

First (outer) pair of parentheses is there to enclose parameter of println method.


#5

Thanks for an immediate clarification!


#6

You're very welcome :smile: