Thursday, May 21, 2020
Ternary Operator - Java Definition
The ternary operator ?: earns its name because its the only operator to take three operands. It is a conditional operator that provides a shorter syntax for the if..then..else statement. The first operand is a boolean expression; if the expression is true then the value of the second operand is returned otherwise the value of the third operand is returned: boolean expression ? value1 : value2 Examples: The following if..then..else statement: boolean isHappy true; String mood ; if (isHappy true) { mood Im Happy!; } else { mood Im Sad!; } can be reduced to one line using the ternary operator: boolean isHappy true; String mood (isHappy true)?Im Happy!:Im Sad!; Generally the code is easier to read when the if..then..else statement is written in full but sometimes the ternary operator can be a handy syntax shortcut.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.