Find square root of a Number in java

There are several ways to find the square root of a particular number in Java. Let’s see some of them.

Program to Find the square root of a Number using java.lang.Math.sqrt() method

 
public class SquareRoot {
 
    public static void main(String args[]) 
    { 
        double positiveValue = 100; 
   
        System.out.println(Math.sqrt(positiveValue));
   
        double negativeValue = -81.00; 
   
        System.out.println(Math.sqrt(negativeValue));
   
        double NaNValue = 0.0/0; 
   
        System.out.println(Math.sqrt(NaNValue)); 
   
        double positiveInfinity = 1.0/0;  
   
        System.out.println(Math.sqrt(positiveInfinity)); 
         
        double  positiveZero = 0.0;
         
        System.out.println(Math.sqrt(positiveZero)); 
    } 
         
}

Output

10.0
NaN
NaN
Infinity
0.0

in above example , public static double sqrt(double x) is used for find square root .

  • x is the value whose square root is returned.
  • If the parameter x is a positive double value, this method returns the square root of x.
  • If the parameter x is NaN or less than zero, this method returns NaN
  • If the parameter x is positive infinity, this method returns positive infinity
  • If the x parameter is positive or negative zero, this method returns the result as zero with the same sign.

Program to Find the square root of a Number without using any in-built method

 class SquareRootCall {

  public static double squareRootMethod(double value) {
    double t;

    double squareroot = value / 2;

    do {
      t = squareroot;
      squareroot = (t + (value / t)) / 2;
    } while ((t - squareroot) != 0);

    return squareroot;
  }
}
 class SquareRoot {

  public static void main(String[] args) {
    double value = 225;
    double squareRoot;
    squareRoot = SquareRootCall.squareRootMethod(value);
    System.out.println("value : " + value);
    System.out.println("Square Root of value : " + squareRoot);
  }
}

Output

value : 225.0
Square Root of value : 15.0

Program to Find the square root of a Number using java.lang.Math.pow() method

  public class SquareRoot {
  
     public static void main(String[] args) 
     {
         Double value=400.0;
         
         Double squareRoot = Math.pow(value, 0.5);
         System.out.println("The Square root of a value  " + value + "  : " + squareRoot);
     }
 }

Output

The Square of a value 400.0 : 20.0