Ternary Operator In Java

  • Eclipse: Oxygen
  • Java: 1.8

Ternary operator works on three operands. It returns a value based on a condition that evaluates to either true or false statement. True and false statements are also an expression that you want to evaluate. If the expression is true it evaluates expression true otherwise it evaluates the expression false.

The ternary operator is also known as a conditional operator that evaluate a condition of if-then-else. In Java “If” statement is used make a decision based on a condition which allows testing a condition if the condition is true, the code inside “if block” will be executed, and else statement will execute when a condition is false.

Ternary operator has three operands: Condition? Expression 1: Expression 2

  1. The condition is evaluated.
  2. If the condition is true then Expression1 is returned.
  3. If the condition is false then Expression2 will be

Ternary operator allows you to evaluate a Boolean expression that evaluates the true or false expression. If the condition is true then it will evaluate expression true otherwise it evaluates the expression false.

Ternary operator examples

Ternary operator allows to returning an output based on the relational operator.

Output

false

Explanation

In this statement, if first operand is greater than second operand (5<4), then the “x” will be assigned with value “true” otherwise “x” will be assigned with value “false”.

This operator allows to returning an output based on multiple conditions. This program will demonstrate the condition based on string datatype.

Output

Not allowed to vote

Explanation

In this code first question mark (?) will check age > 18. If it’s true user will get the output “Allowed to vote”. If it’s false then the user will get the output “Not allowed to vote”.

 

Ternary operator allows you to evaluate two primitive value are equal or not.

Output

0

Explanation

This program demonstrates very clearly. To show the equality operator if one operand is equal to the second operand than the user will get output 1 otherwise the user will get 0 output.

Note- If two primitive values are equal you must use “==” not “=”.

Contributed by: Poonam Tomar


VIEW COURSES

Buy me a coffee!

 

PayTM QR (INDIA)

  • Get video tutorials
  • Project files set
  • Get Certified

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu