package java_dividebyzero; /** * * @web http://java-buddy.blogspot.com/ */ public class Java_DivideByZero { public static void main(String[] args) { System.out.println("\n--- Test Divide By Zero on int: 100/0 ---"); int int1 = 100; int intResult; try{ intResult = int1/0; System.out.println(intResult); }catch (ArithmeticException ex){ System.out.println("catched: " + ex); } System.out.println("\n--- Test Divide By Zero on float: 100/0 ---"); float float1 = 100; float resultFloat; try{ resultFloat = float1/0; System.out.println(resultFloat); System.out.println("resultFloat == Float.POSITIVE_INFINITY : " + (resultFloat == Float.POSITIVE_INFINITY)); System.out.println("resultFloat == Float.NEGATIVE_INFINITY : " + (resultFloat == Float.NEGATIVE_INFINITY)); System.out.println("resultFloat == Float.NaN : " + (resultFloat == Float.NaN)); }catch (ArithmeticException ex){ System.out.println("catched: " + ex); } System.out.println("\n--- Test Divide By Zero on double: -100/0 ---"); double double1 = 100; double resultDouble; try{ resultDouble = -1 * double1/0; System.out.println(resultDouble); System.out.println("resultDouble == Double.POSITIVE_INFINITY : " + (resultDouble == Double.POSITIVE_INFINITY)); System.out.println("resultDouble == Double.NEGATIVE_INFINITY : " + (resultDouble == Double.NEGATIVE_INFINITY)); System.out.println("resultDouble == Double.NaN : " + (resultDouble == Double.NaN)); }catch (ArithmeticException ex){ System.out.println("catched: " + ex); } } }
Sunday, July 27, 2014
Divide a number (int, float, double) by zero
Here show that if you divide a int by zero, it will throw ArithmeticException of by zero. But it you divide a float or double by zero, no exception will be thrown. It return Infinity or -Infinity, and equal to POSITIVE_INFINITY or NEGATIVE_INFINITY.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment