मराठी

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

Advertisements

प्रश्न

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

Explain the following with an example segment:

Ternary Operator

कोड लेखन
स्पष्ट करा
Advertisements

उत्तर

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
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 6: Variables and Expressions - EXERCISE [पृष्ठ १३१]

APPEARS IN

धीरज मेहरोत्रा Computer Science [English] Class 12
पाठ 6 Variables and Expressions
EXERCISE | Q 19. (ii) | पृष्ठ १३१
धीरज मेहरोत्रा Computer Science [English] Class 12
पाठ 6 Variables and Expressions
EXERCISE | Q 29. (v) | पृष्ठ १३१
Advertisements
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×