Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Updated the references to Java 7 and changed to Applicability

The conditional operator ?: uses the boolean value of its first operand to decide which of the other two expressions will be evaluated. (See §15.25, "Conditional Operator ? :," of the Java Language Specification [JLS 20052011].)

The general form of a Java conditional expression is operand1 ? operand2 : operand3.

...

Rule

Operand 2

Operand 3

Resultant type

1

type T

type T

type T

2

boolean

Boolean

boolean

3

Boolean

boolean

boolean

4

null

reference

reference

5

reference

null

reference

6

byte or Byte

short or Short

short

7

short or Short

byte or Byte

short

8

byte, short, char, Byte, Short, Character

constant int

byte, short, char if value of int is representable

9

constant int

byte, short, char, Byte, Short, Character

byte, short, char if value of int is representable

10

other numeric

other numeric

promoted type of the 2nd and 3rd operands

11

T1 = boxing conversion(S1)

T2 = boxing conversion(S2)

apply capture conversion to lub(T1,T2)

See §5.1.7, "Boxing Conversion", "§5.1.10, "Capture Conversion," and §15.12.2.7, "Inferring Type Arguments Based on Actual Arguments," of the Java Language Specification for additional information on the final table entry.

...

Writing the conditional expression as ((i & 1) == 0) ? (short) (i-1)) : workingVal also complies with this guideline because both the second and third operands in this form have type short. However, this alternative is less efficient because it forces unboxing of workingVal on each even iteration of the loop and autoboxing of the result of the conditional expression (from short to Short) on every iteration of the loop.

...

Applicability

When the second and third operands of a conditional expression have different types, they can be subject to unexpected type conversions.

...

Guideline

...

Severity

...

Likelihood

...

Remediation Cost

...

Priority

...

Level

...

EXP55-JG

...

low

...

unlikely

...

medium

...

P2

...

Automated

...

Automated detection of condition expressions whose second and third operands are of different types is straightforward.

...

[Bloch 2005]

Puzzle 8: Dos Equis

[Findbugs 2008]

"Bx: Primitive value is unboxed and coerced for ternary operator"

[JLS 20052011]

§15.25, "Conditional Operator ? :"

...