Find Square Root of a Number in Java
Problem
The square root of x is the non-negative number r for which r × r = x; for example, the square root of 49 is 7.
Given a few numbers, print the square root of each, including a non-perfect square and a negative input.
Java Program
public class SquareRoot {
public static void main(String[] args) {
double[] numbers = {49, 50, 2.25, -9};
for (double x : numbers) {
double root = Math.sqrt(x); // NaN for negative input
System.out.println("sqrt(" + x + ") = " + root);
}
System.out.printf("sqrt(50) to 3 places = %.3f%n", Math.sqrt(50));
}
}Output
Core Logic
Math.sqrt returns the correctly rounded square root as a double, so the interesting part is how it behaves at the edges.
- 1The loop calls
Math.sqrt(x)on each value innumbers. - 2Perfect squares such as 49 come back exact (
7.0); 50 gives a long decimal, the closestdoubleto the true root. - 3A negative input has no real square root, so
Math.sqrtreturnsNaN(not a number) instead of throwing an exception. - 4
printf("%.3f")rounds the result for display without changing the stored value.
Math.sqrt(2.25) is 1.5, because 1.5 × 1.5 = 2.25.Key Point: Check for NaN with Double.isNaN(root) — comparing root == Double.NaN is always false, even when root is NaN.
Key Concepts
Approach 2: Newton's Method
public class SquareRootNewton {
public static void main(String[] args) {
double x = 50;
double guess = x / 2; // any positive starting guess works
int steps = 0;
while (Math.abs(guess * guess - x) > 1e-9) {
guess = (guess + x / guess) / 2; // average the guess with x / guess
steps++;
}
System.out.printf("sqrt(%.0f) = %.6f after %d steps%n", x, guess, steps);
}
}
Output
Core Logic
Newton's method improves a guess by averaging it with x divided by the guess; the error shrinks so fast that a handful of steps reach full precision.
- 1
guessstarts atx / 2; any positive start converges. - 2Each step sets
guess = (guess + x / guess) / 2. - 3If the guess is too big,
x / guessis too small (and the other way round), so their average lands closer to the root. - 4The loop stops once
guess * guessis within1e-9of x.
Key Point: Each step roughly doubles the number of correct digits — the same idea hardware and math libraries use to compute roots quickly.
Why: The number of correct digits roughly doubles per step, so reaching d digits of precision takes about log d iterations.
Key Concepts
Interview Questions
How do you check whether a number is a perfect square?
long r = Math.round(Math.sqrt(n)); return r * r == n; — rounding guards against tiny floating-point errors.
What's the integer square root of a large number?
Use binary search on long values, or BigInteger.sqrt() (Java 9+), when exactness matters.