Operators
Java Program to Demonstrate Ternary Operator
A Java program to demonstrate the usage of the ternary operator.
Problem Description
Write a Java program to find the minimum of two numbers using the ternary operator.
Code
public class TernaryOperator {
public static void main(String[] args) {
int a = 10;
int b = 20;
int min;
// Syntax: variable = (condition) ? expressionTrue : expressionFalse;
min = (a < b) ? a : b;
System.out.println("Minimum Value: " + min);
}
}Output
Minimum Value: 10Explanation
- Ternary Operator (
? :): It is a shorthand forif-elsestatement. - Syntax:
condition ? value_if_true : value_if_false. - If
a < bis true,ais assigned tomin, otherwisebis assigned.
Try Yourself
- Find Maximum: Modify the code to find the maximum of two numbers.
- Even or Odd: Use the ternary operator to check if a number is even or odd.
String result = (n % 2 == 0) ? "Even" : "Odd"; - Absolute Value: Calculate the absolute value of a number using
? :. Hint:(n < 0) ? -n : n - Nested Ternary: Find the largest of three numbers using nested ternary operators.
- Brain Twister: Can you use the ternary operator to print "Positive", "Negative", or "Zero"?
Hint:
(n > 0) ? "Positive" : (n < 0) ? "Negative" : "Zero"
