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

TernaryOperator.java
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: 10

Explanation

  1. Ternary Operator (? :): It is a shorthand for if-else statement.
  2. Syntax: condition ? value_if_true : value_if_false.
  3. If a < b is true, a is assigned to min, otherwise b is assigned.

Try Yourself

  1. Find Maximum: Modify the code to find the maximum of two numbers.
  2. Even or Odd: Use the ternary operator to check if a number is even or odd. String result = (n % 2 == 0) ? "Even" : "Odd";
  3. Absolute Value: Calculate the absolute value of a number using ? :. Hint: (n < 0) ? -n : n
  4. Nested Ternary: Find the largest of three numbers using nested ternary operators.
  5. Brain Twister: Can you use the ternary operator to print "Positive", "Negative", or "Zero"? Hint: (n > 0) ? "Positive" : (n < 0) ? "Negative" : "Zero"