Wiki Markup |
---|
Java is considered to be a safer language than C or C++. The following excerpt is from the Introduction section of Sun's \[[SCG 07|AA. Java References#SCG 07]\]: |
The (Java) language is type-safe, and the runtime provides automatic memory management and range-checking on arrays. These features also make Java programs immune to the stack-smashing and buffer overflow attacks possible in the C and C++ programming languages, and that have been described as the single most pernicious problem in computer security today.
While this statement is in fact true, arithmetic operations in the Java platform require the same caution as in C \and C++. Integer operations can result in overflow or underflow because Java does not provide any indication of these conditions and silently wraps (Java throws only a division by zero exception).
Wiki Markup |
---|
The following excerpt is from the \[[JLS 03|AA. Java References#JLS 03]\] Integer (Overflow): |
The built-in integer operators
...
do not indicate overflow or underflow in any way. Integer operators can throw a
...
NullPointerException
if unboxing conversion of a null reference is required. Other than that, the only integer operators that can throw an exception are the integer divide operator /
...
\ and the integer remainder operator
...
\ %, which throw an
ArithmeticException
if the right-hand operand is zero, and the increment and decrement operators ++ and - which can throw anOutOfMemoryError
if boxing conversion
...
is required and there is not sufficient memory available to perform the conversion.
...
Noncompliant Code Example
...
Code Block | ||
---|---|---|
| ||
public int do_operation(int a, int b)
{
int temp = a + b;
//Could result in overflow
//perform other processing
return temp;
}
|
...
Code Block | ||
---|---|---|
| ||
public int do_operation(int a, int b) throws ArithmeticException
{
long temp = (long)a+(long)b;
if(temp >Integer.MAX_VALUE || temp < Integer.MIN_VALUE) throw ArithmeticException;
else //Value within range can perform the addition
//Do stuff
return (int)temp;
}
|
...