Witscale Test Center

9.4 Binary operators > 9.4.4 Arithmetic erroneous conditions


9.4.4 Arithmetic erroneous conditions

The unary operators + - ++ -- and binary operators * / % + and – are all related to arithmetic operations. The results of these operations are accurate most of the times. Sometimes however, you may not get the results you expect. This is largely due to the limitations while representing numbers. For instance, if you multiply two very large numbers and store the result in narrower data type, an overflow may occur. Java anticipates some of these errors and has specific conventions while dealing with them:

 

1. If you divide any number by 0, the mathematical answer is infinity. However, when you write a Java code that divide a integral number by 0, Java throws a runtime exception called the ArithmeticException.

 

int a = 4,b = 0;

int result = a / b;  // java.lang.ArithmeticException: / by zero

 

This exception may also be thrown when you use modulo operator to find a remainder. The modulo operator implicitly performs division to get the remainder. Therefore, you will get ArithmeticException if the second operand is 0 in a modulo operation. For example, the following code compiles but throws exception at runtime.

 

int a = 4,b = 0;

int result = a % b;  // java.lang.ArithmeticException: / by zero

 

2. Java does not throw exception for any other arithmetic operation. It will simply complete the operation even if the result is arithmetically incorrect. For example, the following code divides 5 by 2, the mathematical answer should be 2.5. However, java completes the operation with result 2 without throwing any exceptions.

 

int a = 5,b = 2;

int result = 5/2;  // No error, the result is 2

 

3. The division by zero and the other erroneous conditions do not throw the ArithmeticException in case of floating-point operands. Java follows IEEE 754 standard for most of its floating-point operations. Like integral arithmetic, the floating-point operations may result in out-of range values such as positive and negative infinity or values, which is not-a-number. The java.lang.Float and java.lang.Double classes define naming constants to represent these values. For example, the Float.NaN value represents the result of certain invalid operations such as dividing zero by zero. Following code does not throw any exception.

 

float a = 0.0f,b = 0.0f;

float result = a/b;    // Value of result is Float.NaN

 

The value of result is Float.NaN after execution