Find Square root of Number sqrt() Java


java.lang.Math class comes with many methods to do simple basic numeric operations. One such one is sqrt() method which returns the square root of a number passed as parameter.

One advantage of Math class methods is that they are declared as static so that they can be called without the need of object creation.

Following is the Math class signature as defined in java.lang package.

public final class Math extends Object

Following is the method signature as defined in Math class

public static double sqrt(double a)

This method takes a double value as parameter and returns a double value of the square root of the value passed as parameter.

  1. If the parameter passed is a negative value (below 0 value), the sqrt() function returns NaN (Not a Number).
  2. If the parameter is positive infinity, the result will be in positive infinity.
  3. If the parameter is negative infinity, the result will be in negative infinity.
  4. The same way with positive zero or negative zero.
Even a whole number is passed, the returned result will be a double value only. It is shown in the following example on "Find Square root of Number sqrt() Java".
public class MathFunctionDemo
{
  public static void main(String args[])
  {
    int a = 25;		        //  integer
    double b = 25.5;		//  positive double value

    int c = -25;		//  negative integer value
    double d = -25.5;		//  negative double value
    int e = 0;		        //  positive zero value
    int f = -0;		        //  negative zero value

    System.out.println("Square root of 25: " + Math.sqrt(a));     
    System.out.println("Square root of 25.5: " + Math.sqrt(b));	

    System.out.println("\nFollowing two square roots prints NaN as they are less than zero");

    System.out.println("Square root of -25: " + Math.sqrt(c));
    System.out.println("Square root of -25.5: " + Math.sqrt(d));

    System.out.println("\nFollowing two square roots prints 0 as 0 is treated as neutral");

    System.out.println("Square root of 0: " + Math.sqrt(e));
    System.out.println("Square root of -0: " + Math.sqrt(f));
  }
}


Find Square root of Number sqrt() Java
Output screenshot on Find Square root of Number sqrt() Java

If required a whole number, cast the result to int value as follows.

System.out.println("Square root of 25: " + (int) Math.sqrt(a));

Leave a Comment

Your email address will not be published.