Java Reference
In-Depth Information
System.out.print(trueExp ? alpha : ((char) i)); // Prints A
}
}
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 NUM12-EX0 of NUM12-J, “Ensure conversions of numeric types to nar-
rower types do not result in lost or misinterpreted data” in The CERT ®
Oracle ®
Secure
Coding Standard for Java [Long 2012].
Noncompliant Code Example
This noncompliant code example prints 100 as the size of the HashSet rather than the ex-
pected result (some value between 0 and 50):
Click here to view code image
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 % 2) == 1) ? i-1 : workingVal);
}
System.out.println(s.size());
}
}
The combination of values of types short and int in the second argument of the con-
ditional expression (the operation i-1 ) causes the result to be an int , as specified by the
integer promotion rules. Consequently, the Short object in the third argument is unboxed
intoa short ,whichisthenpromotedtoan int .Theresultoftheconditionalexpressionis
thenautoboxedintoanobjectoftype Integer .Becausethe HashSet containsonlyvalues
of type Short , the call to HashSet.remove() has no effect.
Search WWH ::




Custom Search