English

Explain the Syntax of the Ternary Operator with an Example Program.

Advertisements

Questions

Explain the Syntax of the Ternary Operator with an Example Program.

Explain the following with an example segment:

Ternary Operator

Code Writing
Explain
Advertisements

Solution

In Java, the Ternary Operator (? :) is used to evaluate a condition and select one of two expressions based on whether the condition is true or false. It provides a shorter alternative to an if-else statement.

Syntax:

variable = (condition) ? expression1 : expression2;
  • condition: It is a Boolean expression that evaluates to either true or false.
  • expression1: This expression is evaluated if the condition is true.
  • expression2: This expression is evaluated if the condition is false.

Example:

class TernaryOperator 
{
    public static void main(String[] args) 
    {
        int a = 10;
        int b = 20;
        int max = (a > b) ? a : b;
        System.out.println("Greater Number: " + max);
    }
}

Output:

Greater Number: 20
  • In the above program, two integer variables a and b are initialised with the values 10 and 20, respectively. The ternary operator evaluates the condition a > b to determine the greater number.
  • Since 10 is less than 20, the condition is false. Therefore, the value of b, which is 20, is assigned to the variable max. Finally, the System.out.println() statement displays Greater Number: 20 as the output.
shaalaa.com
  Is there an error in this question or solution?
Chapter 6: Variables and Expressions - EXERCISE [Page 131]

APPEARS IN

Dheeraj Mehrotra Computer Science [English] Class 12
Chapter 6 Variables and Expressions
EXERCISE | Q 19. (ii) | Page 131
Dheeraj Mehrotra Computer Science [English] Class 12
Chapter 6 Variables and Expressions
EXERCISE | Q 29. (v) | Page 131
Advertisements
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×