Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Result type determination begins from the top of the table; the compiler applies the first matching rule. The Operand 2 and Operand 3 columns refer to operand2 and operand3 (from the previous definition) respectively. In the table, constant int refers to constant expressions of type int (such as '0' or variables declared final).

Rule

Operand 2

Operand 3

Resultant typeType

1

type Type Ttype

Type T

type 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 Other numericother

Other numeric

promoted Promoted type of the 2nd and 3rd operands

11

T1 = boxing conversion(S1)

T2 = boxing conversion(S2)

apply 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.

...

In this noncompliant code example, the programmer expects that both print statements will print the value of alpha as a charA. The first print statement prints A because the compiler applies the eighth rule 8 from the result type determination table to determine that the second and third operands of the conditional expression are, or are converted to, type char. However, the second print statement prints 65 — the —the value of alpha as an int. The first matching rule from the table is the tenth rule 10. Consequently, the compiler promotes the value of alpha to type int.

Code Block
bgColor#FFCCCC
public class Expr {
  public static void main(String[] args) {
    char alpha = 'A';
    int i = 0;
    /* otherOther code. Value of i may change */
    boolean trueExp = ...; // some expression that evaluates to true
    System.out.print(trueExp ? alpha : 0); // prints A
    System.out.print(trueExp ? alpha : i); // prints 65
  }
}

...

Bibliography

[Bloch 2005]

Puzzle 8: , "Dos Equis"

[Findbugs 2008]

"Bx: Primitive value is unboxed and coerced for ternary operatorValue Is Unboxed and Coerced for Ternary Operator"

[JLS 2011]

§15.25, "Conditional Operator ? :"

 

...