Open In App

Java sqrt() method with Examples

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.




// 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));
    }
}


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.




// 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);
    }
}


Output:

NaN
Infinity
NaN


Last Updated : 09 Apr, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads