Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the use of integer variables throw an exception?

I have come across with the following two codes. Why does it not throw an exception for floating point where as in other case it will throw a runtime exception.

class FloatingPoint
    {
      public static void main(String [] args)
       {
         float a=1000f;
         float b=a/0;
        System.out.println("b=" +b);
       }
    }

OUTPUT:b=Infinity.

If I try with int values then it will throw a runtime exception. Why is it like this?

like image 659
giri Avatar asked Aug 01 '10 04:08

giri


People also ask

What happens when exception is thrown?

When an exception is thrown using the throw keyword, the flow of execution of the program is stopped and the control is transferred to the nearest enclosing try-catch block that matches the type of exception thrown. If no such match is found, the default exception handler terminates the program.

What happens in integer numbers if the size is greater than the value?

It will cause integer overflow error. The value of each integer variable is stored in a block of memory of a fixed size.

How to handle integer parse exception in Java?

We have used the parseInt method of the Integer class before. The method throws a NumberFormatException if the string it has been given cannot be parsed into an integer. The above program throws an error if the user input is not a valid number. The exception will cause the program execution to stop.

Why the ID of float values are different when the same value is assigned to two different variables?

In that case the float value containing variable may contain same data but reason behind is to mathematical rules. The only two value are consider after the point & remaining are value get neglected. so the we get two different addresses of the same data containing variables.


1 Answers

The short answer

Integral types (JLS 4.2.1) are categorically different from floating point types (JLS 4.2.3). There may be similarities in behavior and operations, but there are also characteristically distinguishing differences such that confusing the two can lead to many pitfalls.

The difference in behavior upon division by zero is just one of these differences. Thus, the short answer is that Java behaves this way because the language says so.


On integral and floating point values

The values of the integral types are integers in the following ranges:

  • byte: from -128 to 127, inclusive, i.e. [-27, 27-1]
  • short: from -32768 to 32767, inclusive, i.e. [-215, 215-1]
  • int: from -2147483648 to 2147483647, inclusive, i.e. [-231, 231-1]
  • long: from -9223372036854775808 to 9223372036854775807, inclusive, i.e. [-263, 263-1]
  • char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535, i.e. [0, 216-1]

The floating-point types are float and double, which are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations.

Their values are ordered as follows, from smallest to greatest:

  • negative infinity,
  • negative finite nonzero values,
  • positive and negative zero (i.e. 0.0 == -0.0),
  • positive finite nonzero values, and
  • positive infinity.

Additionally, there are special Not-a-Number (NaN) values, which are unordered. This means that if either (or both!) operand is NaN:

  • numerical comparison operators <, <=, >, and >= return false
  • numerical equality operator == returns false
  • numerical inequality operator != returns true

In particular, x != x is true if and only if x is NaN.

For e.g. double, the infinities and NaN can be referred to as:

  • Double.POSITIVE_INFINITY
  • Double.NEGATIVE_INFINITY
  • Double.NaN, testable with helper method boolean isNaN(double)

The situation is analogous with float and Float.


On when exceptions may be thrown

Numerical operations may only throw an Exception in these cases:

  1. NullPointerException, if unboxing conversion of a null reference is required
  2. ArithmeticException, if the right hand side is zero for integer divide/remainder operations
  3. OutOfMemoryError, if boxing conversion is required and there is not sufficient memory

They are ordered by importance, with regards to being common source for pitfalls. Generally speaking:

  • Be especially careful with box types, as just like all other reference types, they may be null
  • Be especially careful with the right hand side of an integer division/remainder operations
  • Arithmetic overflow/underflow DOES NOT cause an exception to be thrown
  • Loss of precision DOES NOT cause an exception to be thrown
  • A mathematically indefinite floating point operation DOES NOT cause an exception to be thrown

On division by zero

For integer operation:

  • Division and remainder operations throws ArithmeticException if the right hand side is zero

For floating point operation:

  • If the left operand is NaN or 0, the result is NaN.
  • If the operation is division, it overflows and the result is a signed infinity
  • If the operation is remainder, the result is NaN

The general rule for all floating point operation is as follows:

  • An operation that overflows produces a signed infinity.
  • An operation that underflows produces a denormalized value or a signed zero.
  • An operation that has no mathematically definite result produces NaN.
  • All numeric operations with NaN as an operand produce NaN as a result.

Appendix

There are still many issues not covered by this already long answer, but readers are encouraged to browse related questions and referenced materials.

Related questions

  • What do these three special floating-point values mean: positive infinity, negative infinity, NaN?
  • In Java what does NaN mean.
  • When can Java produce a NaN (with specific code question)
  • Why does (360 / 24) / 60 = 0 … in Java (distinguish integer vs floating point operations!)
  • Why null == 0 throws NullPointerException in Java? (beware the danger of boxed primitives!)
  • Is 1/0 a legal Java expression? (absolutely!!!)
like image 146
polygenelubricants Avatar answered Nov 07 '22 17:11

polygenelubricants