Java Math nextUp()

That is, if the argument is 6.7, then the adjacent number of 6.7 in direction of positive infinity is 6.700000000000001.

The syntax of the nextUp() method is:

Math.nextUp(start)

Note: The nextUp() method is a static method. Hence, we can call the method directly using the class name Math.


nextUp() Parameters

  • start - starting number whose adjacent number is returned

Note: The data type of start can be either float or double.


nextUp() Return Values

  • returns the number adjacent to start towards positive infinity
  • returns NaN if start is NaN
  • returns positive infinity if start is positive infinity

Note: The nextUp() method is equivalent to the Math.nextAfter(start, Double.POSITIVE_INFINITY).


Example: Java Math.nextUp()

class Main {
  public static void main(String[] args) {

    // float arguments
    float start1 = 7.9f;
    System.out.println(Math.nextUp(start1));  // 7.9000006

    // double arguments
    double start2 = 7.9;
    System.out.println(Math.nextUp(start2));  // 7.900000000000001

    // with positive infinity
    double infinity = Double.POSITIVE_INFINITY;
    System.out.println(infinity);            // Infinity

    // with NaN
    double nan = Math.sqrt(-5);
    System.out.println(Math.nextUp(nan));    // NaN

  }
}

Here, we have used the Java Math.sqrt(-5) method to calculate the square root of -5. Since, the square root of a negative number is not a number, Math.nextUp(nan) returns NaN.

The Double.POSITIVE_INFINITY is a field of Double class that allows us to implement infinity in a program.


Also Read:

Did you find this article helpful?