Java - Calculate the square root, Math.sqrt()

You can find the square root with Math.sqrt(). sqrt stands for Square root, which means square root.

Math.sqrt() has the form:

public static double sqrt(double a)

Features include:

  • Passing a as an argument returns the square root of a
  • If 0 is passed as an argument, 0 is returned.
  • If you pass a negative number or NaN (Not a Number) as an argument, NaN is returned.

Example

You can calculate the square root as

double x = 25;
double y = 225;

System.out.println("Math.sqrt(x)=" + Math.sqrt(x));
System.out.println("Math.sqrt(y)=" + Math.sqrt(y));

Output:

Math.sqrt(x)=5.0
Math.sqrt(y)=15.0

If you pass a negative number as an argument, NaN is returned, like this:

double negative = -5;
result = Math.sqrt(negative);
System.out.println(result);

Output:

NaN

Infinity is returned when an infinite value is passed as an argument as follows.

double infinity = Double.POSITIVE_INFINITY;
result = Math.sqrt(infinity);
System.out.println(result);

Output:

Infinity

If you pass NaN as an argument as follows, NaN is returned.

double nan = Double.NaN;
result = Math.sqrt(nan);
System.out.println(result);

Output:

NaN
codechachaCopyright ©2019 codechacha