Ternary Operator Flashcards

1
Q

Define a ternary operator !

A

The Java ternary operator is a shorthand way of writing an if-else statement, using the syntax condition ? valueIfTrue : valueIfFalse. It evaluates the condition; if true, it returns the first value, and if false, it returns the second.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Give all required and optional parts in a ternary operator !

A

The ternary operator consists of three parts:

  1. Condition: The expression that evaluates to true or false.
  2. Value if true: The result if the condition is true.
  3. Value if false: The result if the condition is false.

There are no optional parts in the ternary operator itself; all three components are necessary.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Give data types required for every operand in a ternary operator !

A

In Java, the ternary operator condition ? expr1 : expr2 requires that both expr1 and expr2 are of compatible types. The type of the result is determined by the common supertype of expr1 and expr2. If they are of different types, an implicit cast might occur. The condition must be a boolean expression.

NOTE

The expressions in a ternary operator do need to be compatible, but the way they are evaluated can involve boxing and type promotion, especially with primitives.

Here’s the key takeaway:

  1. Expressions must be compatible: The Java compiler checks for compatibility based on the types involved.
  2. Boxing: If one expression is a primitive, it can be automatically boxed to its corresponding wrapper class, allowing it to be compatible with reference types.

So while the expressions must be compatible, the presence of automatic boxing can sometimes obscure this requirement. In practice, you won’t run into a compilation error with the primitive/reference mix due to this boxing behavior

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Give a common pitfall involving a ternary operator !

A

There is no requirement that second and third expressions in ternary operations have
the same data types except if it is combined with an assignement operator like in the following example

int animal=y>1 ? 21 : “ZEBRA”; // DOES NOT COMPILE

How well did you know this?
1
Not at all
2
3
4
5
Perfectly