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).
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?