WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Software Engineering · Basic · question 18 of 100

What is a ternary operator, and how is it used in programming?

📕 Buy this interview preparation book: 100 Software Engineering questions & answers — PDF + EPUB for $5

A ternary operator is a conditional operator that takes three operands. It is used to simplify code that involves a simple conditional expression.

The syntax of the ternary operator is as follows:

(condition) ? (if true) : (if false)

Here, ‘condition‘ is the Boolean expression that is evaluated. If the expression is ‘true‘, the operator returns the ‘if true‘ value; otherwise, it returns the ‘if false‘ value.

For example, consider the following code that determines whether a number is even or odd:

int num = 10;
if (num % 2 == 0) {
    System.out.println("Even");
} else {
    System.out.println("Odd");
}

The above code can be simplified using the ternary operator as follows:

int num = 10;
String result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(result);

In this case, the ‘condition‘ is ‘num

Ternary operators can also be nested, allowing for more complex conditional expressions. For example:

int num = 10;
String result = (num > 0) ? ((num % 2 == 0) ? "Positive even" : "Positive odd") : "Negative";
System.out.println(result);

In this example, the nested ternary operator first checks if ‘num‘ is positive or negative. If positive, it then checks if it is even or odd. If negative, it simply returns ‘"Negative"`.

In summary, ternary operators are used to simplify conditional expressions in programming by allowing for a more concise syntax. They are especially useful in cases where there is a simple true/false decision to be made.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Software Engineering interview — then scores it.
📞 Practice Software Engineering — free 15 min
📕 Buy this interview preparation book: 100 Software Engineering questions & answers — PDF + EPUB for $5

All 100 Software Engineering questions · All topics