Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
Does JVM throw Exceptions for Floating-point arithmetic operations?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ: Does JVM throw Exceptions for Floating-point arithmetic operations?

Does JVM throw Exceptions for Floating-point arithmetic operations?

According to 3.8 Floating-Point Arithmetic. The JVM throws no Exception as a result of any floating-point operations. Special values, such as positive and negative infinity or NaN, are returned as the result of suspicious operations such as positive value, negative value and zero division by zero. For example,

class Program {
  public static void main(String[] args) {
    double d1 = 1.0;
    double d2 = 0.0;
    byte b =1;
    d1 = d1/d2;
    b = (byte)d1;
    System.out.print(b);
  }
}

The output is -1 and no exception throw. The process involved is:

  • 1.0/0.0 results in Double.POSITIVE_INFINITY;
  • Double.POSITIVE_INFINITY is converted to Integer.MAX_VALUE ('0' followed by 31 '1's)
  • Integer.MAX_VALUE is then cast to byte value, which simply takes the last 8 bits(11111111) and is -1.

 

From IEEE 754 standards:

The values +infinity and -infinity are denoted with an exponent of all '1's and a fraction of all 0s. The sign bit distinguishes between negative infinity and positive infinity. Being able to denote infinity as a specific value is useful because it allows operations to continue past overflow situations.

Floating-point value d1 is converted to byte in two steps (5.1.3 Narrowing Primitive Conversions: First the value is converted to int then the int is converted to byte.

  • NaN is converted to int 0 then to byte 0.
  • Negative infinity is converted to Integer.MIN_VALUE (0x80000000) which is converted to byte 0.
  • Positive infinity is converted to Integer.MAX_VALUE (0x7FFFFFFF) which is converted to byte -1 (0xFF).

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help