The cast technique is much better than it may seem to be at first sight.

Conversion from int to double is exact.

Math.sqrt is specified, for normal positive numbers, to return "the double value closest to the true mathematical square root of the argument value". If the input was a perfect square int, the result will be an integer-valued double that is in the int range.

Similarly, conversion of that integer-valued double back to an int is also exact.

The net effect is that the cast technique does not introduce any rounding error in your situation.

If your program would otherwise benefit from use of the Guava intMath API, you can use that to do the square root, but I would not add dependency on an API just to avoid the cast.

Answer from Patricia Shanahan on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ ref_math_sqrt.asp
Java Math sqrt() Method
System.out.println(Math.sqrt(0)); System.out.println(Math.sqrt(1)); System.out.println(Math.sqrt(9)); System.out.println(Math.sqrt(0.64)); System.out.println(Math.sqrt(-9)); ... The sqrt() method returns the square root of a number.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-math-sqrt-method
Java Math sqrt() Method - GeeksforGeeks
The Math.sqrt() method is a part of java.lang.Math package. This method is used to calculate the square root of a number. This method returns the square root of a given value of type double.
Published ย  May 13, 2025
Discussions

Java Square Root Integer Operations Without Casting? - Stack Overflow
I'm working with a program that uses a perfect square grid in all circumstances, and I need to obtain the square root in integer form. Is the only way to do this to cast the argument as an int and then return an int-casted double? ... If you're talking about java.util.Map, then you would have ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Java square root calculator? - Stack Overflow
Ok, I'm a beginner in java, learning on my own through websites and books. I tried a simple square root calculator with a for loop and a while loop (I've included what I tried below). Sadly, all my... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Utility Method to find the Square root of a number - Code Review Stack Exchange
Utility to calculate the square root of a number. The method also accept an epsilon value, which controls the precision. The epsilon value could range to any number including zero. I am expecting a More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
May 12, 2015
algorithm - How do I compute the square root of a number without using builtins? - Stack Overflow
To find a square root, you simply need to find a number which, raised to the power of 2 (although just multiplying by itself is a lot easier programmatically ;) ) gives back the input. More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ math.sqrt() in java
Math.sqrt() Method in Java - Scaler Topics
April 28, 2024 - Again, the square root of the given number is big enough that it cannot be stored in int data type. Math.sqrt() in Java is a method that uses precision to find the square root of any number of double types.
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ library โ€บ math โ€บ sqrt
Java Math sqrt()
System.out.println(Math.sqrt(value1)); // Infinity // square root of a positive number
Find elsewhere
๐ŸŒ
Medium
medium.com โ€บ edureka โ€บ java-sqrt-method-59354a700571
How to Calculate Square and Square Root in Java? | Edureka
September 18, 2020 - This article discusses about the different ways to find square and square root in Java.
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 8 โ€บ docs โ€บ api โ€บ java โ€บ lang โ€บ Math.html
Math (Java Platform SE 8 )
4 days ago - If the argument is equal to 10n for integer n, then the result is n. The computed result must be within 1 ulp of the exact result. Results must be semi-monotonic. ... Returns the correctly rounded positive square root of a double value.
๐ŸŒ
Quora
quora.com โ€บ How-can-we-write-a-Java-program-to-find-the-square-root-of-a-number
How can we write a Java program to find the square root of a number? - Quora
6)else if your ans lies in upper half,then adjust start=mid+1; Thus you can determine square root using binary search. ... Studied Electronics and Communication Engineering & Embedded Systems (Graduated 2018) ยท Author has 116 answers and 139.9K answer views ยท 8y ... Level up your Java code with IntelliJ IDEA.
๐ŸŒ
Codecademy
codecademy.com โ€บ docs โ€บ java โ€บ math methods โ€บ .sqrt()
Java | Math Methods | .sqrt() | Codecademy
September 3, 2022 - The Math.sqrt() method returns the positive, properly rounded square root of a double-type value. ... Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ valid-perfect-square
Valid Perfect Square - LeetCode
Can you solve this real interview question? Valid Perfect Square - Given a positive integer num, return true if num is a perfect square or false otherwise. A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself.
๐ŸŒ
Python Tutor
pythontutor.com โ€บ visualize.html
Python Tutor - Visualize Code Execution
Free online compiler and visual debugger for Python, Java, C, C++, and JavaScript. Step-by-step visualization with AI tutoring.
Top answer
1 of 1
2

Duplicated logic

Avoid duplicated logic like this:

public static boolean closeEnough(double a, double x, double epsilon) {
    return (Math.abs(x - ((a / x) + x) / 2)) <= epsilon;
}

public static double betterGuess(double a, double x) {
    return ((a / x) + x) / 2;
}

The closeEnough method includes the exact same logic as betterGuess. Make it a habit to look at duplicated code fragments with suspicion.

If you eliminate the duplication, the code becomes:

public static boolean closeEnough(double a, double x, double epsilon) {
    return (Math.abs(x - betterGuess(a, x))) <= epsilon;
}

public static double betterGuess(double a, double x) {
    return ((a / x) + x) / 2;
}

... but then, does this actually make sense? Calling betterGuess from closeEnough? Not really. How can you check if a candidate square root is close enough? You cannot compare with the real square root, because that's the target unknown. What you can compare with, is the original number, which you should be able to get by squaring:

public static boolean closeEnough(double a, double x, double epsilon) {
    return Math.abs(a - x * x) <= epsilon;
}

This implementation is more logical, and has another positive side effect: it makes it possible to clean up the squareRoot method with the suspicious 0-check:

public static double squareRoot(final double a, final double epsilon) {
    if (a == 0)
        return a;
    else
        return internalSqrRoot(a, a / 2, epsilon);
}

The method can become simply:

public static double squareRoot(final double a, final double epsilon) {
    return internalSqrRoot(a, a / 2, epsilon);
}

It would seem the 0-check was there to prevent a division by zero problem in Math.abs(x - ((a / x) + x) / 2))

Method visibility

The MathUtil class name suggests it's a utility class, but the public MathUtil.betterGuess method (to name just one) doesn't seem very useful. It's an implementation detail that should be hidden, so make it private. Question the other methods too, and change their visibility as appropriate.

The variable names are quite poor. For example in closeEnough it's impossible to tell if the target number is a or x. target and candidate might have been better names.

Input validation

More than just commenting "Function takes a non-negative real number ", it would be better to enforce that by throwing an IllegalArgumentException.

Poor JavaDoc

This kind of JavaDoc is worse than no JavaDoc at all:

/**
 * Method internalSqrRoot.
 *
 * @param a double
 * @param x double
 * @param epsilon double
 * @return double
 */

It's worse, because tells nothing new about the method, but since it's there, I've read it, in vain.

Minor things

  • It's recommended to use braces even with single-line if statements
  • Redundant parentheses in the expression (Math.abs(x - ((a / x) + x) / 2))
  • Perhaps instead of internalSqrRoot, squareRootHelper might be a better name. Or, since the method has a different signature than squareRoot, it can just as well be squareRoot (overloading)
๐ŸŒ
Level1Techs
forum.level1techs.com โ€บ dev zone โ€บ code
Java Math.sqrt is not working - Code - Level1Techs Forums
May 30, 2022 - SquareRoot = (Button)findViewById(R.id.SquareRoot); SquareRoot.setOnClickListener(new OnClickListener() { public void onClick(View v) { x = TextBox.getText(); xconv = Double.parseDouble(x.toString()); Math.sqrt(xconv); answer = Double.toStr...
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Math โ€บ sqrt
Math.sqrt() - JavaScript | MDN
July 10, 2025 - The square root of x, a nonnegative number. If x < 0, returns NaN. Because sqrt() is a static method of Math, you always use it as Math.sqrt(), rather than as a method of a Math object you created (Math is not a constructor). ... Math.sqrt(-1); // NaN Math.sqrt(-0); // -0 Math.sqrt(0); // 0 ...
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ why we can't use int or float with math.sqrt ?
r/javahelp on Reddit: Why we can't use int or float with Math.sqrt ?
September 17, 2023 -

I'm a beginner and came to calculating square root of a number part. Lesson says I need to use double with Math.sqrt
int number = 42;
double squareRoot = Math.sqrt(number);
and I was curious why we can't use int or float. I searched on google but couldn't find an answer.

๐ŸŒ
AmbitionBox
ambitionbox.com โ€บ interviews โ€บ brane-enterprises-question โ€บ write-java-code-to-find-square-root-without-mathsqrt-GdsfUzBy
Write Java code to find the square root without using Math.s
Prepare for your next job interview with AmbitionBox. Read 12 Lakh+ interview questions & answers shared by real candidates across 1 Lakh+ companies in India.