Open In App

Infinity or Exception in Java when divide by 0?

Consider the following code snippets:




public class Geeksforgeeks
{
    public static void main(String[] args)
    {
        double p = 1;
        System.out.println(p/0);
    }
}

Output:

Infinity




public class Geeksforgeeks
{
    public static void main(String[] args)
    {
        int p = 1;
        System.out.println(p/0);
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Geeksforgeeks.main(Geeksforgeeks.java:8)

Explanation: In the first piece of code, a double value is being divided by 0 while in the other case an integer value is being divide by 0. However the solution for both of them differs.

Article Tags :