Versions Compared

Key

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

Wiki MarkupThe conditional operator {{?:}} uses the {{boolean}} value of one expression to decide which of the other two expressions should be evaluated \[[JLS 2005|AA. Bibliography#JLS 05]\]. The conditional operator is syntactically right-associative. For instance {{a?b:c?d:e?f:g}} is equivalent to {{a?b:(c?d:(e?f:g))}}. evaluated (see JLS Section 15.25 "Conditional Operator ? :").

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

  • If the value of the first operand (operand1) is true, then the second operand expression (operand2) is chosen
  • If the value of the first operand is false, then the third operand expression (operand3) is chosen

The conditional operator is syntactically right-associative; for example, a?b:c?d:e?f:g is equivalent to a?b:(c?d:(e?f:g)).

The JLS-defined rules for determining guidelines (tabulated below) used by a Java compiler to determine the type of the result of a conditional expression (tabulated below) are quite complicated and may result in unexpected type conversions. The first matching guideline, starting ; programmers may be surprised by the type conversions required for expressions they have written.

Result type determination begins from the top of the table, is applied. In the table, * ; the compiler applies the first matching rule. The table refers to constant expressions of type int (such as '0' or variables declared final) , as constant int; the "Operand 2 refers " and "Operand 3" columns refer to operand2 in the general form of a Java conditional given above, and Operand 3 refers to operand3: and operand3 (from the above definition), respectively.

Operand 2

Operand 3

Resultant type

type T

type T

type T

boolean

Boolean

boolean

Boolean

boolean

boolean

null

reference

reference

reference

null

reference

byte or Byte

short or Short

short

short or Short

byte or Byte

short

byte, short, char

const constant int*

byte, short, char if value of int is representable

const constant int*

byte, short, char

byte, short, char if value of int is representable

Byte

const constant int*

byte if int is representable as byte

const constant int*

Byte

byte if int is representable as byte

Short

const constant int*

short if int is representable as short

const constant int*

Short

short if int is representable as short

Character

const constant int*

char if int is representable as char

const constant int*

Character

char if int is representable as char

other numeric

other numeric

promoted type of the 2nd and 3rd operands

T1 = boxing conversion (S1)

T2 = boxing conversion(S2)

apply capture conversion to lub(T1,T2)

See JLS Section 5.1.7 "Boxing Conversion," JLS Section 5.1.10 "Capture Conversion" and JLS Section 15.12.2.7 "Inferring Type Arguments Based on Actual Arguments" for additional information on the final table entry.

The complexity of the rules that Because of the complicated nature of the rules used to determine the result type of a conditional expression and the possibility of can lead to unintended type casting, it is recommended that conversions. Thus, the second and third operands of the each conditional expression should always have the same type. This recommendation also applies to boxed primitives.

...

This noncompliant code example prints the value of alpha as A, which is of the char type. The third operand '0', is a constant expression of type int, whose value 0 can be represented as a char and hence does not cause any ; numeric promotion is unnecessary. However, this behavior depends on the particular value of the constant integer expression. Changing the value of the constant integer expression ; changing that value may lead to different behavior, as will be demonstrated in the second noncompliant code example.

Code Block
bgColor#FFCCCC
public class Expr {
  public static void main(String[] args) {
    char alpha = 'A';
    System.out.print(true  ? alpha  : 0);
  }
}

Compliant Solution

This compliant solution recommends the use of the same uses identical types for the second and third operands of the conditional expressions. The clearer semantics help avoid confusionexpression; the explicit cast clarifies the expected type.

Code Block
bgColor#ccccff
public class Expr {
  public static void main(String[] args) {
    char alpha = 'A';
    // Cast 0 as a char to explicitly state that the type of the 
    // conditional expression should be char.
    System.out.print(true  ? alpha  : ((char) 0));
  }
}

...

This noncompliant example prints 65 instead of the expected A. 65 is the ASCII equivalent of A. This happens because — instead of the numeric promotion of expected A, because the second operand (alpha) must be promoted to an type int. The numeric promotion occurs because the value of the third operand (the constant expression '12345') is of type int and consequently, inappropriate for being too large to be represented as a char.

Code Block
bgColor#FFCCCC
public class Expr {
  public static void main(String[] args) {
    char alpha = 'A';
    System.out.print(true  ? alpha  : 12345);
  }
}

Compliant Solution

The compliant solution casts alpha to int for explicitly stating states the intended result type by casting alpha to type (int) of the conditional expression. While casting . Casting 12345 to type char ensures would ensure that both operands in of the conditional expression have the same type (, and would result in A being printed). However, it results would result in data loss when an integer larger than Character.MAX_VAUEVALUE is downsized downcast to a type char. This compliant solution casts avoids potential truncation by casting alpha to type int, the wider of the operand types, to avoid this issue.

Code Block
bgColor#ccccff
public class Expr {
  public static void main(String[] args) {
    char alpha = 'A';
    // Cast alpha as an int to explicitly state that the type of the 
    // conditional expression should be int.
    System.out.print(true  ? ((int) alpha)  : 12345);
  }
}

...

This noncompliant code example prints 65 instead of A. This is because of numeric promotion of The third operand is a variable of type int, so the second operand (alpha to an int, which happens because the third operand, variable i, is an ) must be converted to type int.

Code Block
bgColor#FFCCCC
public class Expr {
  public static void main(String[] args) {
    char alpha = 'A';
    int i = 0;
    System.out.print(true ? alpha : i);
  }
}

...

This compliant solution declares i as a type char, ensuring that the second and third operands of the conditional expression have the same type.

...

Wiki Markup
This noncompliant code example uses boxed and unboxed primitives of different types in the conditional expression. Consequently, the {{Integer}} object is auto-unboxed to its primitive type {{int}} and then coercedconverted to the primitive type {{float}}., This resultsresulting in loss of precision. \[[Findbugs 2008|AA. Bibliography#Findbugs 08]\]. (sic)

Code Block
bgColor#FFCCCC
public class Expr {
  public static void main(String[] args) {
    Integer i = Integer.MAX_VALUE;
    float f = 0;       
    System.out.print(true ? i : f);
  }
}

...

Code Block
bgColor#ccccff
public class Expr {
  public static void main(String[] args) {
    Integer i = Integer.MAX_VALUE;
    Integer f = 0; //declare as Integer
    System.out.print(true ? i : f);
  }
}

Risk Assessment

If the types of When the second and third operands in of a conditional expression are not the same then the result of the conditional expression may be unexpectedhave different types, they may be subject to type conversions that were not anticipated by the programmer.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

EXP14-J

low

unlikely

medium

P2

L3

Automated Detection

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

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

Bibliography

Wiki Markup
\[[JLS 2005|AA. Bibliography#JLS 05]\] [Section 15.25, Conditional Operator ? :|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.25]
\[[Bloch 2005|AA. Bibliography#Bloch 05]\] Puzzle 8: Dos Equis
\[[Findbugs 2008|AA. Bibliography#Findbugs 08]\] "Bx: Primitive value is unboxed and coerced for ternary operator"
\[[JLS 2005|AA. Bibliography#JLS 05]\] [Section 15.25, Conditional Operator ? :|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.25]

...

EXP13-J. Consistently use the symbolic constants you define      04. Expressions (EXP)      05. Scope (SCP)