Page 348 - Computer_Science_F5
P. 348
Program Example 5.10:
Java program to implement the Ternary Operator
int a = 10; Chapter Five: Object oriented programming with Java
FOR ONLINE READING ONLY
int b = 20;
// Using the ternary operator to determine the larger of two numbers
int max = (a > b) ? a : b;
System.out.println(“The maximum value is “ + max);
Output: The maximum value is 20
(g) Conditional operator ( ? : )
Since the conditional operator has three operands, it is referred as the ternary
operator.
This operator consists of three operands and is used to evaluate Boolean expressions.
The goal of the operator is to decide, which value should be assigned to the variable.
The operator is written as – variable x = (expression) ? value if true : value if false
Program Example 5.11:
Java program to implement the Conditional Operator
public class example{
public static void main(String args[])
{
int a, b;
a = 10;
b = (a == 0) ? 20: 30;
System.out.println( “b : “ + b );
}
}
Output:
339
Student’s Book Form Five
Computer Science Form 5.indd 339 23/07/2024 12:34

