Menu
Topics Index
...
`


Operators >
Siva Nookala - 12 Apr 2016
About Ternary Operator In Java :
Ternary operator can be used to replace certain types of if-then-else statements. It is called ternary operator because it uses three operands.

The syntax for ternary operator is:
expression1 ? expression2 : expression3

expression1 can be any expression that evaluates to boolean value, if expression1 is true the expression2 is evaluated else expression3 is evaluated.
int marks = 80;
int bonus = marks > 60 ? 5 : 2;
If marks are greater than 60, a bonus of 5 marks are given else 2 marks will be given.
Ternary Example
class TernaryExample
{
    public static void main(String arg[])
    {
        int marks = 50;
        int bonus = marks > 60 ? 5 : 2;
        int total_marks = marks + bonus;
        char grade = total_marks > 75 ? 'A' : 'B';
        
        System.out.println("Marks = " + marks);
        System.out.println("Bonus = " + bonus);
        System.out.println("Total Marks = " + total_marks);
        System.out.println("Grade = " + grade);
    
    }
}
OUTPUT

Marks = 50
Bonus = 2
Total Marks = 52
Grade = B

DESCRIPTION

This example uses ternary operator twice, once to decide how many bonus marks to give and once to assign grade to the student. Since marks are 50, which are less than 60, so the statement marks > 60 is false hence a bonus marks of 2 is given. Since the total_marks are 52 (marks = 50, bonus = 2), which is less than 75 the grade 'B' is assigned.

THINGS TO TRY
  • Change the value of marks to 65 and see the output. The bonus value will change from 2 to 5.
  • Declare two variables as shown below.
    int a = 10;
    int b = 20;
    Now write the code to print the variable which is having the highest value using a ternary operator.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.