4

I heard one twist in java. If anyone know proper reason you're asked to share it. Question is:

double result1 = 1.0/0.0;
sop(result1); // output Infinity
double result2 = 0.0/0.0;
sop(result2); // output NaN

the same is happening for float variable also. but for int type its raising ArithmeticException. Why?

Note: I am using jdk 1.7

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Sridhar K
  • 37
  • 4

2 Answers2

3

You cannot represent infinity or NAN using an int.

From JLS

The result of a floating-point division is determined by the rules of IEEE 754 arithmetic:

Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.

Check the IEEE explanation

Why doesn't division by zero (or overflow, or underflow) stop the program or trigger an error? Why does a standard on numbers include "not-a-number" (NaN)? The 754 model encourages robust programs. It is intended not only for numerical analysts but also for spreadsheet users, database systems, or even coffee pots. The propagation rules for NaNs and infinities allow inconsequential exceptions to vanish. Similarly, gradual underflow maintains error properties over a precision's range.

When exceptional situations need attention, they can be examined immediately via traps or at a convenient time via status flags. Traps can be used to stop a program, but unrecoverable situations are extremely rare. Simply stopping a program is not an option for embedded systems or network agents. More often, traps log diagnostic information or substitute valid results.

Flags offer both predictable control flow and speed. Their use requires the programmer be aware of exceptional conditions, but flag stickiness allows programmers to delay handling exceptional conditions until necessary.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

Infinity or undefined numbers are not a part of the integer set, so they are excluded from int and Integer. This is the same in most programming languages, not in Java per se.

But the real reason is historical, of course. Integers used to be represented using 2-complement binary logic. It was not in the standards that there was a NaN or Infinity.

Rob Audenaerde
  • 19,195
  • 10
  • 76
  • 121