Menu
Topics Index
...
`

Ternary Example - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App