Java sqrt() method with Examples

The java.lang.Math.sqrt() returns the square root of a value of type double passed to it as argument. If the argument is NaN or negative, then the result is NaN. If the argument is positive infinity, then the result is positive infinity. If the argument passed is positive zero or negative zero then the result will be same as that of the argument.

Syntax:

public static double sqrt(double a)
Parameter :
a : the value whose square root is to be returned.
Return :
This method returns the positive square root value of 
the argument passed to it.

Example 1: To show working of java.lang.Math.sqrt() method.



filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate working
// of java.lang.Math.sqrt() method
import java.lang.Math;
  
class Gfg {
  
    // driver code
    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));
    }
}

chevron_right


Output:

5.477225575051661
6.708203932499369
7.745966692414834
9.486832980505138

Example 2: To show working of java.lang.Math.sqrt() method when argument is NaN or +infinity.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate working
// of java.lang.Math.sqrt() method
import java.lang.Math; // importing java.lang package
  
public class GFG {
    public static void main(String[] args)
    {
  
        double positiveInfinity = Double.POSITIVE_INFINITY;
        double negativeVal = -5;
        double nan = Double.NaN;
        double result;
  
        // Here argument is negative,
        // output will be NaN
        result = Math.sqrt(negativeVal);
        System.out.println(result);
  
        // Here argument is positive infinity,
        // output will also positive infinity
        result = Math.sqrt(positiveInfinity);
        System.out.println(result);
  
        // Here argument is NaN, output will be NaN
        result = Math.sqrt(nan);
        System.out.println(result);
    }
}

chevron_right


Output:

NaN
Infinity
NaN


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.