🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

Ternary Operator in Java  


Introduction

  • The ternary operator in Java is a shortcut for the if-else statement.
  • It evaluates a boolean expression and returns one of two values based on the result of the evaluation.
  • The syntax of ternary operator is as below:
    condition ? value1 : value2;
    • condition: The boolean expression that is evaluated.
    • value1: The value returned if the condition evaluates to true.
    • value2: The value returned if the condition evaluates to false.
  • Usage:
    • Simplified if-else: Instead of writing an entire if-else block, the ternary operator allows you to decide between two values in one line.
  • Program:
    public class TernaryOperator
    {
        public static void main(String[] args)
        {
            int a = 10, b = 20;
    
            // Using ternary operator to find the maximum of two numbers
            int max = (a > b) ? a : b;
            System.out.println("The maximum value is: " + max);  // Output: The maximum value is: 20
    
            // Using ternary operator to check if a number is even or odd
            String result = (a % 2 == 0) ? "Even" : "Odd";
            System.out.println("The number is: " + result);  // Output: The number is: Even
    
            // Nested ternary operator
            int largest = (a > b) ? ((a > 15) ? a : 15) : ((b > 15) ? b : 15);
            System.out.println("The largest value is: " + largest);  // Output: The largest value is: 20
        }
    }
    Output:
    The maximum value is: 20
    The number is: Even
    The largest value is: 20
  • Program Explanation:
    • Finding Maximum Value:
      • int max = (a > b) ? a : b;
      • The ternary operator checks whether a > b. Since a is 10 and b is 20, it returns b (20) because the condition is false.
    • Even/Odd Check:
      • String result = (a % 2 == 0) ? "Even" : "Odd";
      • This checks if a is divisible by 2 (i.e., whether it is even). Since a = 10 is even, the result is "Even".
    • Nested Ternary Operator:
      • int largest = (a > b) ? ((a > 15) ? a : 15) : ((b > 15) ? b : 15);
      • This is an example of a nested ternary operator. First, it checks if a is greater than b. If a is greater, it further checks if a is greater than 15; if so, it returns a, otherwise it returns 15. If b is greater than a, it checks if b is greater than 15; if so, it returns b, otherwise it returns 15.
When to Use Ternary Operator :-
  1. Assignments: For assigning values based on conditions.
    • Example: int result = (score > 50) ? 1 : 0;
  2. Return Statements: For returning a value based on a condition.
    • Example: return (age >= 18) ? "Adult" : "Minor";
  3. Simple Conditional Logic: For simple checks, the ternary operator provides a cleaner, more compact alternative to if-else statements.
When Not to Use Ternary Operator :-
  1. Complex Conditions: If the condition is too complicated or the ternary operator becomes hard to read, it’s better to use traditional if-else blocks.
  2. Multiple Statements: The ternary operator is not suitable when multiple statements need to be executed in each branch (for example, in the if or else block).
Some Advance Important Points :-
  • Concise Syntax:
    • The ternary operator is used to perform conditional logic in a single line, making the code more compact.
    • Example: int max = (a > b) ? a : b;.
  • Return Values:
    • The ternary operator returns one of two values depending on the condition. The values must be of the same type or compatible types.
  • Type Consistency:
    • Both value1 and value2 in the ternary operator must be of the same type or must be compatible types.
    • Example: We cannot have one value as an int and another as a String unless there’s an explicit type cast.
  • Nested Ternary Operator:
    • We can nest ternary operators within each other, but excessive nesting can make the code harder to read.
    • Example: int largest = (a > b) ? ((a > 15) ? a : 15) : ((b > 15) ? b : 15);.
  • Short-Circuit Evaluation:
    • The ternary operator performs short-circuit evaluation, meaning the second expression (value2) is only evaluated if the condition is false.
    • This is similar to the && and || operators.