Infinity in Java

  1. Use Double to Implement Infinity in Java
  2. Use Float to Implement Infinity in Java
  3. Use Division With Zero to Implement Infinity in Java

This tutorial discusses methods to implement infinity in Java. There are several mathematical scenarios where one might need to implement infinity for mathematical operations.

Use Double to Implement Infinity in Java

The Double class in Java supports infinity. You can implement positive infinity or negative infinity. The below example demonstrates this.

import java.util.*;

public class MyClass {
    public static void main(String args[]) {
        double posInf = Double.POSITIVE_INFINITY;
        double negInf = Double.NEGATIVE_INFINITY;
        System.out.println(posInf);
        System.out.println(negInf);
    }
}

Output:

Infinity
-Infinity

Use Float to Implement Infinity in Java

The Float class in Java also supports infinity. You can implement positive infinity or negative infinity with the Float class. The below example illustrates this.

import java.util.*;

public class MyClass {
    public static void main(String args[]) {
        float posInf = Float.POSITIVE_INFINITY;
        float negInf = Float.NEGATIVE_INFINITY;
        System.out.println(posInf);
        System.out.println(negInf);
    }
}

Output:

Infinity
-Infinity

Use Division With Zero to Implement Infinity in Java

We can also simply divide a number with zero to implement infinity in Java. The below example illustrates this.

public class Main {
    public static void main(String[] args) {
        System.out.println(1.0/0.0);
        System.out.println(-1.0/0.0);
        double inf = 1.0/0.0;
        double negInf = -1.0/0.0;
    }

}

Output:

Infinity
-Infinity

Related Article - Java Math

  • Do Power in Java