Conditional Operator (`?:`) in Java
The conditional operator ( ?: ) — The Only Ternary Operator is one of the most useful operators in Java. It lets you write simple decision-making logic in a single line, making your code cleaner and more concise. It's also a favorite topic in Java interviews because of its syntax, nesting behavior, and type compatibility rules. In this article, you'll learn: What the conditional operator is Why it's called a ternary operator Syntax and working Nested conditional operators Difference between ?: and if-else Practical examples Interview questions Memory tricks What is the Conditional Operator? The conditional operator is represented by: ? : It is the only ternary operator in Java . A ternary operator takes three operands , unlike: Operator Type Number of Operands Example Unary 1 ++x , !flag , ~5 Binary 2 a + b , a > b , a && b Ternary 3 (a > b) ? a : b Syntax result = ( condition ) ? valueIfTrue : valueIfFalse ; How It Works condition │ Is it true? / \ Yes No │ │ valueIfTrue valueIfFalse │ │ └────── Result ──────┘ If the condition is true , Java returns the value before the colon ( : ). If the condition is false , Java returns the value after the colon ( : ). Example 1 int x = ( 10 > 20 ) ? 30 : 40 ; System . out . println ( x ); Output 40 Step-by-Step Evaluate the condition: 10 > 20 ↓ false Since the condition is false, Java selects the value after : . 40 Therefore, x = 40 Example 2: Finding the Maximum int a = 10 ; int b = 20 ; int max = ( a > b ) ? a : b ; System . out . println ( max ); Output 20 This is one of the most common uses of the conditional operator. Example 3: Even or Odd int number = 7 ; String result = ( number % 2 == 0 ) ? "Even" : "Odd" ; System . out . println ( result ); Output Odd Example 4: Absolute Value int x = - 5 ; int absolute = ( x < 0 ) ? - x : x ; System . out . println ( absolute ); Output 5 Nested Conditional Operators One of the biggest advantages of the conditional operator is that it can be nested . Example int x = ( 10 > 20 ) ? 30 :