CODE
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);
}
}
Marks = 50
Bonus = 2
Total Marks = 52
Grade = B
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.
marks
to 65
and see the output. The bonus
value will change from 2
to 5
.int a = 10;
int b = 20;
ternary
operator.