Java Math sqrt() Method (original) (raw)

Last Updated : 13 May, 2025

The **Math.sqrt() method is a part of java.lang.Math package. This method is used to calculate the square root of a number. This method returns the square root of a given value of type double. In this article, we are going to discuss how this method works for regular values and for special cases such as infinity and NaN.

**Special Cases:

These special cases make sure that the **Math.sqrt() methods work correctly.

Syntax of sqrt() Method

public static double sqrt(double a)

Now, we are going to discuss some examples for better understanding and clarity.

Examples of Java Math sqrt() Method

**Example 1: In this example, we will see the **square root of positive numbers.

Java `

// Java program to demonstrate the // working of Math.sqrt() method import java.lang.Math;

class Geeks {

public static void main(String args[]) {
    
    double a = 30;
    System.out.println(Math.sqrt(a));  

    a = 45;
    System.out.println(Math.sqrt(a));  

    a = 60;
    System.out.println(Math.sqrt(a));

    a = 90;
    System.out.println(Math.sqrt(a));
}

}

`

Output

5.477225575051661 6.708203932499369 7.745966692414834 9.486832980505138

**Explanation: Here, we are calculating the square root of different numbers like 30, 45, 60 and 90.

**Example 2: In this example, we will see how the sqrt() method handles special cases like **NaN, negative values and posititve infinity.

Java `

// Java program to demonstrate working // of Math.sqrt() method for special cases import java.lang.Math;

public class Geeks {

public static void main(String[] args) {
    
    double p = Double.POSITIVE_INFINITY;
    double n = -5;
    double nan = Double.NaN;
    double res;

    // Here the agument is negative
    res = Math.sqrt(n);
    System.out.println(res);  

    // Here the argument is positive infinity
    res = Math.sqrt(p);
    System.out.println(res); 

    // Here the argument is NaN
    res = Math.sqrt(nan);
    System.out.println(res);  
}

}

`

**Explanation: Here, we are handling special cases such as NaN and Infinity. When the given argument is negative and NaN then we will get NaN as an output, and when the argument is positive infinity then we will get infinity.