JAVA | Explain the use of ternary (?:) operator with example.

Java ternary operator is the only conditional operator that takes three operands. Java ternary operator is a one liner replacement for if-then else statement and used a lot in java programming.
 
The first operand in java ternary operator should be a boolean or a statement with boolean result. If the first operand is true then java ternary operator returns second operand else it returns third operand. 

Syntax of java ternary operator is:
result = testStatement ? value1:value2;
If testStatement is true then value1 is assigned to result variable else value2 is assigned to result variable. java ternary operator can be used to avoid if-then-else and switch case statements. This way we can
reduce the number of lines of code in java program.  
 
Example:
class test
{
public static void main(String args[])
{
int a=5;
String result=””;
result = (a>0 ?”positive” : ”negative”);
System.out.println(result); 
}}


Post a Comment

0 Comments