💎Common Ternary Operator Statements

Here's a list of common ternary operator statements that are often used in interviews:

Assign variable based on a condition:

int num = 10;
String result = (num > 5) ? "Greater than 5" : "Less than or equal to 5";
int num = 10;
System.out.println(num % 2 == 0 ? "Even" : "Odd");

Return value based on condition:

public int getNumberType(int num) {
  return (num > 0) ? 1 : (num < 0) ? -1 : 0; 
}

Set variable to max of two values:

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

Conditionally instantiate object:

boolean condition = true;
MyClass obj = condition ? new MyClass() : null; 

So in summary, the ternary operator is very useful for writing compact conditional logic to assign values, return results, print messages, instantiate objects, etc. based on an expression evaluating to true or false.

Last updated