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 avoid an java.util.ConcurrentModificationException with ArrayList?
- How to convert a given array to a list in Java?
- How to make Java objects eligible for garbage collection?
- What are local variables in Java?
- What are instance variables in Java?
- How many backslashes?
- What are class variables in Java?
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(24745)
- What is runtime polymorphism in Java?(18326)
- How to add BASIC Authentication into HttpURLConnection?(16083)
- What is String literal pool?(14754)
- Can the run() method be called directly to start a thread?(13991)
- What does Class.forname method do?(10593)
- Can transient variables be declared as 'final' or 'static'?(10445)