...
While this statement is true, arithmetic operations in the Java platform require as much caution as in C and C++. Integer operations can result in overflow because Java does not provide any indication of overflow conditions and silently wraps (Java arithmetic throws an exception only on a division by zero).
Wiki Markup |
---|
TheAccording following excerpt is from to the Java Language Specification \[[JLS 03|AA. Java References#JLS 03]\], section 4.2.2 Integer Operations: |
...
If the result of the addition is greater than the maximum value or less than the minimum value that the int
type can represent, then the variable temp
will contain an erroneous result. Unlike C and C++ integer overflows are harder to exploit in Java. For example, if temp
has a negative value as a result of an overflow and is used as an array index, java.lang.ArrayIndexOutOfBoundsException
) results in Java, whereas this is a more pernicious issue in C and C++ because memory regions outside the array bounds can be maliciously altered. In Java, wrapped values typically result in incorrect computations and unanticipated outcomes.
Compliant Solution (Bounds Checking)
In Java, wrapped values typically result in incorrect computations and unanticipated outcomes.
Compliant Solution (Bounds Checking)
Explicitly check the range of each arithmetic operation and throw an Explicitly check the range of each arithmetic operation and throw an ArithmeticException
on overflow. When performing operations on values of type int
or smaller, the arithmetic can be done using variables of type long
. For performing arithmetic operations on numbers of type long
, the BigInteger
Class must be used.
...
The remainder operation is safer in Java than the corresponding modulo operator in C/C++.has the following behavior for corner cases:
- If the modulo of
Integer.MIN_VALUE
with -1 is taken the result is always 0 in Java.
- If the right-hand operand is zero, then the integer remainder operator % will throw an
ArithmeticException
.
...
The shift operation in Java is quite different from C/C++,has the following properties:
- The right shift is an arithmetic shiftThe right shift is an arithmetic shift, while in C/C++ it is implementation defined (logical or arithmetic).
- The types
boolean, float and double
cannot use the bit shifting operators.
- In C/C++ if the value being left shifted is negative or the right-hand operator of the shift operation is negative or greater than or equal to the width of the promoted left operand, there is undefined behavior. This does not extend to Java. If the value to be shifted is of type
int
, only the five lowest-order bits of the right-hand operand are used as the shift distance. That is, the shift distance is the value of the right-hand operand masked by 31 (0x1F). This results in a value modulo 31, inclusive.
...