Versions Compared

Key

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

...

The complexity of the rules that determine the result type of a conditional expression can lead to unintended type conversions. Consequently, the second and third operands of each conditional expression should have identical types. This recommendation also applies to boxed primitives.

Noncompliant Code Example

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 does print A because the compiler applies the eighth rule 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 value of alpha as an int. The first matching rule from the table above is the tenth rule; 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;
    /* other 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
  }
}

Compliant Solution

This compliant solution uses identical types for the second and third operands of each conditional expression; the explicit casts specify the type expected by the programmer.

...

Note that the explicit cast in the first conditional expression is redundant; that is, the value printed remains identical whether the cast is present or absent. Nevertheless, use of the redundant cast is good practice; it serves as an explicit indication of the programmer's intent and, consequently, improves maintainability. When the value of i in the second conditional expression falls outside the range that can be represented as a char, the explicit cast will truncate its value. This usage complies with exception EXP13-EX1 of guideline "NUM00-J. Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data."

Noncompliant Code Example

This noncompliant code example prints 100 as the size of the HashSet rather than the expected result (some value between 0 and 50). The combination of values of types short and int in the second argument of the conditional expression (the operation i-1) causes the result to be an int, as specified by the normal integer promotion rules. Consequently, the Short object in the third argument is autounboxed into a short, which is then promoted into an int. The result of the conditional expression is then autoboxed into an object of type Integer. Because the HashSet contains only values of type Short, the call to HashSet.remove() has no effect.

Code Block
bgColor#FFCCCC
public class ShortSet {
  public static void main(String[] args) {
    HashSet<Short> s = new HashSet<Short>();
      for (short i = 0; i < 100; i++) {
        s.add(i);
        // Cast of i-1 is safe, because value is always representable
        Short workingVal = (short) (i-1);
        ... // other code may update workingVal

        s.remove(((i & 1) == 0) ? i-1 : workingVal);
      }
    System.out.println(s.size());
  }
}

Compliant Solution

This compliant solution casts the second operand to type short, then explicitly invokes the Short.valueOf method to create a Short instance whose value is i - 1. Consequently, the second and third operands of the conditional expression both have type Short, and the remove() call has the expected result.

...

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

Risk Assessment

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

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

EXP12-J

low

unlikely

medium

P2

L3

Automated Detection

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

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4a34cddc76819aad-d97ee5f2-49684326-8e588fbf-47c68fee185e6aea0df84229"><ac:plain-text-body><![CDATA[

[[Bloch 2005

AA. Bibliography#Bloch 05]]

Puzzle 8: Dos Equis

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="92a53bdb9ccff419-995c0882-45b54474-83978d28-3a6103d5146e2aac3ac6a208"><ac:plain-text-body><![CDATA[

[[Findbugs 2008

AA. Bibliography#Findbugs 08]]

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

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="df0daa77084ed089-3922cb50-468d4d4d-869281ba-81c3c89276ca6fe591f7c7a6"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

[§15.25, "Conditional Operator ? :"

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.25]

]]></ac:plain-text-body></ac:structured-macro>

...