Thursday, December 11, 2025
HomeLanguagesJavaInfinity or Exception in Java when divide by 0?

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.

  • In case of double/float division, the output is Infinity, the basic reason behind that it implements the floating point arithmetic algorithm which specifies a special values like “Not a number” OR “infinity” for “divided by zero cases” as per IEEE 754 standards.
  • In case of integer division, it throws ArithmeticException.

This article is contributed by Pranjal Mathur. If you like Lazyroar and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32444 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6813 POSTS0 COMMENTS
Nicole Veronica
11950 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12026 POSTS0 COMMENTS
Shaida Kate Naidoo
6945 POSTS0 COMMENTS
Ted Musemwa
7197 POSTS0 COMMENTS
Thapelo Manthata
6890 POSTS0 COMMENTS
Umr Jansen
6881 POSTS0 COMMENTS