Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
135 views
in JAVA by (178k points)
Can the ternary operator be nested in Java?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

Yes, the ternary operator can be nested, meaning that one or both expressions of a ternary operator can be another ternary operator. This is known as a nested ternary operator.

For example, consider the following code snippet:

int a = 10, b = 20, c = 30;
int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
 

In this example, we have three integer variables a, b, and c, and we want to find the maximum value among them using a nested ternary operator.

The outer ternary operator checks if a is greater than b. If it is true, then the nested ternary operator (a > c) ? a : c is evaluated. This nested ternary operator checks if a is greater than c, and returns a if true, otherwise returns c.

If the condition (a > b) in the outer ternary operator is false, then the nested ternary operator (b > c) ? b : c is evaluated, which checks if b is greater than c, and returns b if true, otherwise returns c.

Finally, the value of the maximum variable is assigned to max.

Note that while nesting ternary operators can make the code more concise, it can also make it harder to read and understand, especially for complex conditions.

Related questions

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...