Versions Compared

Key

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

...

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

Noncompliant Code Example

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 coerced to the primitive {{float}}. This results in loss of precision. \[[Findbugs 08|AA. Java References#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);
  }
}

Compliant Solution

This compliant solution declares both the operands as Integer.

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 the second and third operands in a conditional expression are not the same then the result of the conditional expression may be unexpected.

...

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

...

04. Expressions (EXP)      04. Expressions (EXP)      EXP01-J. Ensure a null pointer is not dereferenced