Java Math sqrt()

The Java Math sqrt() method returns the square root of the specified number.

The syntax of the sqrt() method is:

Math.sqrt(double num)

Here, sqrt() is a static method. Hence, we are accessing the method using the class name, Math.

sqrt() Parameters

The sqrt() method takes a single parameter.

  • num - number whose square root is to be computed

sqrt() Return Values

  • returns square root of the specified number
  • returns NaN if the argument less than 0 or NaN

Note: The method always returns the positive and correctly rounded number.

Example: Java Math sqrt()

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

    // create a double variable
    double value1 = Double.POSITIVE_INFINITY;
    double value2 = 25.0;
    double value3 = -16;
    double value4 = 0.0;

    // square root of infinity
    System.out.println(Math.sqrt(value1));  // Infinity

    // square root of a positive number
    System.out.println(Math.sqrt(value2));  // 5.0

    // square root of a negative number
    System.out.println(Math.sqrt(value3));  // NaN

    // square root of zero
    System.out.println(Math.sqrt(value4));  // 0.0

In the above example, we have used the Math.sqrt() method to compute the square root of infinity, positive number, negative number, and zero.

Here, Double.POSITIVE_INFINITY is used to implement positive infinity in the program.

When we pass an int value to the sqrt() method, it automatically converts the int value to the double value.

int a = 36;

Math.sqrt(a);   // returns 6.0

Recommended Tutorials