Understanding the Ternary Operator in Java

Introduction

The ternary operator in Java is a concise way to perform conditional operations. It is a shorthand for an if-else statement, which evaluates a boolean expression and returns one of two values based on whether the expression is true or false.

Syntax of the Ternary Operator

condition ? value_if_true : value_if_false;
      

Key Points:

Examples of the Ternary Operator

1. Basic Example

int number = 10;
String result = (number > 0) ? "Positive" : "Negative";
System.out.println(result);
      

Output:

Positive

2. Nested Ternary Operator

int number = 0;
String result = (number > 0) ? "Positive" : (number < 0) ? "Negative" : "Zero";
System.out.println(result);
      

Output:

Zero

3. Using the Ternary Operator for Multiple Conditions

int age = 20;
String eligibility = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";
System.out.println(eligibility);
      

Output:

Eligible to vote

4. Simplifying if-else with Ternary Operator

int a = 15, b = 20;
String larger = (a > b) ? "a is larger" : "b is larger";
System.out.println(larger);
      

Output:

b is larger

Common Examples of the Ternary Operator

Example 1: Check if a Number is Even or Odd

int number = 15;
String result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println(result);
      

Example 2: Find the Largest of Two Numbers

int a = 10, b = 20;
String result = (a > b) ? a + " is larger" : b + " is larger";
System.out.println(result);
      

Example 3: Check if a Year is a Leap Year

int year = 2024;
String result = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) ? year + " is a leap year" : year + " is not a leap year";
System.out.println(result);
      

Unsolved Problems

  1. Write a program to check if a number is divisible by both 2 and 3 using a ternary operator.
  2. Write a program to check if a character entered by the user is a vowel or consonant using the ternary operator.
  3. Write a program to find the smallest of three numbers using the ternary operator.
  4. Write a program to check if a number is positive, negative, or zero using the ternary operator.
  5. Write a program to check for a leap year using ternary operator.