Java Ternary Operator

Ternary operator replaces the following code


\begin{lstlisting}
if (expression) {
number = 10;
}
else {
number = -10;
}
\end{lstlisting}

With


\begin{lstlisting}
number = (expression) ? expressionTrue : expressinFalse;
\end{lstlisting}

Why name ternary operator? Because it uses 3 operands. Here, expression is a boolean expression which evaluates to either true or false. If it evaluates to true, expressionTrue is evaluated and assigned to variable number. If it evaluates to False, expressionFalse is evaluated and assigned to variable number.


\begin{lstlisting}
class Operator {
public static void main(String[] args) {
\...
...sitive'';
System.out.println(number + '' is '' + result);
}
}
\end{lstlisting}

When you run the program, the output will be: -5.5 is not positive.



Subsections