Java Program to Find the Square Root of a Number
The square root of a number x is the value that, multiplied by itself, gives x. It is written √x. For example, √9 = 3 because 3 × 3 = 9, and √2 ≈ 1.41421.
Negative numbers have no real square root. In Java, Math.sqrt() returns NaN (not a number) for them.
1. Square Root Using Math.sqrt()
Math.sqrt() takes a double and returns its square root as a double. It is the standard way to do this in Java.
import java.util.Scanner;
public class SquareRoot {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double number = scanner.nextDouble();
scanner.close();
if (number < 0) {
System.out.println("Negative numbers have no real square root.");
} else {
System.out.println("Square root of " + number + " is " + Math.sqrt(number));
}
}
}
Enter a number: 64 Square root of 64.0 is 8.0
Enter a number: 2 Square root of 2.0 is 1.4142135623730951
Enter a number: -9 Negative numbers have no real square root.
2. Square Root Using Math.pow()
A square root is the same as raising a number to the power ½, so Math.pow(x, 0.5) gives the same result. The same idea gives other roots, such as the cube root with an exponent of 1.0 / 3.
public class SquareRootPow {
public static void main(String[] args) {
double number = 36;
double squareRoot = Math.pow(number, 0.5);
double cubeRoot = Math.pow(27, 1.0 / 3);
System.out.println("Square root of " + number + " is " + squareRoot);
System.out.printf("Cube root of 27 is %.1f%n", cubeRoot);
}
}
Square root of 36.0 is 6.0 Cube root of 27 is 3.0
3. Square Root Without Built-in Methods
Newton's method finds a square root by repeated improvement. Start with a guess g; a better guess is the average of g and x / g. Repeat until the guess stops changing noticeably.
public class SquareRootNewton {
static double squareRoot(double x) {
if (x == 0) {
return 0;
}
double guess = x;
while (Math.abs(guess * guess - x) > 1e-10 * x) {
guess = (guess + x / guess) / 2;
}
return guess;
}
public static void main(String[] args) {
double[] numbers = {81, 2, 0.25};
for (double n : numbers) {
System.out.printf("Square root of %s is %.5f%n", n, squareRoot(n));
}
}
}
Square root of 81.0 is 9.00000 Square root of 2.0 is 1.41421 Square root of 0.25 is 0.50000
4. Summary
Math.sqrt(x)returns the square root ofxas adouble.Math.pow(x, 0.5)gives the same result, and other exponents give other roots.Math.sqrt()returnsNaNfor negative numbers, so check the input first.- Newton's method,
guess = (guess + x / guess) / 2, finds a square root without library methods.