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
trueorfalse. - 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
aandbare initialised with the values10and20, respectively. The ternary operator evaluates the conditiona > bto determine the greater number. - Since
10is less than20, the condition isfalse. Therefore, the value ofb, which is20, is assigned to the variablemax. Finally, theSystem.out.println()statement displays Greater Number: 20 as the output.
shaalaa.com
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 6: Variables and Expressions - EXERCISE [पृष्ठ १३१]
