Java Math sqrt()

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

Example

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

// compute square root of 25 System.out.println(Math.sqrt(25));
} } // Output: 5.0

Syntax of Math.sqrt()

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

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges