Java Math sqrt()

sqrt() accepts a double value as an argument, and returns the correctly rounded positive square root of the argument. The return value is of type double.

Following is the syntax of sqrt() method.

double value = sqrt(double x)

Since the definition of sqrt() function has double datatype as argument, you can pass int, float or long as arguments; because these datatypes could implicitly promote to double.

We shall learn about some of the special cases for sqrt() method with examples.

Example 1 – Math.sqrt(double)

In the following example, we use sqrt() method to find the square root of 10.

Java Program

public class MathExample {
	public static void main(String[] args) {
		double x = 10;
		double sqrt_x = Math.sqrt(x);
		System.out.println(sqrt_x);
	}
}

Output

3.1622776601683795
ADVERTISEMENT

Example 2 – Math.sqrt(int)

In the following example, we pass an int value for the argument to sqrt() method.

Java Program

public class MathExample {
	public static void main(String[] args) {
		int x = 4;
		double sqrt_x = Math.sqrt(x);
		System.out.println(sqrt_x);
	}
}

Output

2.0

Similarly, you can provide a float or long value as argument to sqrt() method.

Example 3 – Math.sqrt(NaN)

In the following example, we pass Double.NaN as argument to sqrt() method. As per the definition of the sqrt() in Math class, the method should return NaN value.

Java Program

public class MathExample {
	public static void main(String[] args) {
		double x = Double.NaN;
		double sqrt_x = Math.sqrt(x);
		System.out.println(sqrt_x);
	}
}

Output

NaN

Example 4 – Math.sqrt() – With Positive Infinity as Argument

In the following example, we pass Double.POSITIVE_INFINITY as argument to sqrt() method. As per the definition of the sqrt() method in Math class, the method should return positive infinity.

Java Program

public class MathExample {
	public static void main(String[] args) {
		double x = Double.POSITIVE_INFINITY;
		double sqrt_x = Math.sqrt(x);
		System.out.println(sqrt_x);
	}
}

Output

Infinity

Example 5 – Math.sqrt() – With Negative Infinity as Argument

In the following example, we pass Double.POSITIVE_INFINITY as argument to sqrt() method. As per the definition of the sqrt() method in Math class, the method should return NaN for negative infinity as input value.

Java Program

public class MathExample {
	public static void main(String[] args) {
		double x = Double.NEGATIVE_INFINITY;
		double sqrt_x = Math.sqrt(x);
		System.out.println(sqrt_x);
	}
}

Output

NaN

Conclusion

In this Java Tutorial, we learned about Java Math.sqrt() function, with example programs.