Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

The Ternary (?) Operator in Java

[post-views]

 

In this lesson, you will learn,

  • Ternary Operator (?) in Java
  • Examples

 

Ternary Operator (?) in Java

  • The ternary operator in Java is a concise, conditional operator that can be used to replace certain types of if-else statements.
  • It takes three operands (hence the name “ternary”) and is a shorthand for deciding which of two expressions to evaluate based on a given condition.

 

Syntax

condition ? expression1 : expression2;

 

Here, condition is a boolean expression.

If the condition evaluates to true, expression1 is evaluated and becomes the result of the operation. If condition is false, expression2 is evaluated and becomes the result.

 

Example 1: Basic Usage

Using the ternary operator to assign the greater of two numbers to a variable.

public class TernaryExample {
    public static void main(String[] args) {
        int a = 5, b = 10;
        int max = (a > b) ? a : b;
        System.out.println("The greater number is " + max);
    }
}

 

Output

The greater number is 10

 

Example 2: Even and odd

public class TernaryPrintExample {
    public static void main(String[] args) {
        int number = 3;
        String result = (number % 2 == 0) ? "Even" : "Odd";
        System.out.println(number + " is " + result);
    }
}

 

Output

3 is Odd

 

Example 3: Nested Ternary Operator

public class NestedTernaryExample {
    public static void main(String[] args) {
        int a = 10, b = 20, c = 15;
        int largest = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
        System.out.println("The largest number is " + largest);
    }
}

 

Output

The largest number is 20

 


End of the lesson….enjoy learning

 

Student Ratings and Reviews

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review