...
While this statement is true, arithmetic operations in the Java platform require just as much caution their as do the analogous operations in C and C++, because integer operations in Java can still result in overflow. Java does not provide any indication of overflow conditions and silently wraps. While integer overflows in vulnerable C and C++ programs can result in the execution of arbitrary code; in Java, wrapped values typically result in incorrect computations and unanticipated outcomes.
...
Code Block | ||
---|---|---|
| ||
public int magnitude(int i) { return Math.abs(i); } |
If When Integer.MIN_VALUE
(â“2,147,483,648) is passed to Math.abs()
, the result is Integer.MIN_VALUE
, not rather than the expected -Integer.MIN_VALUE
, because -Integer.MIN_VALUE
is not representable cannot be represented as an int
.
Compliant Solution (Math.abs()
)
...