For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
The square root of a number x is a value y such that y2 = x. In Java, square roots are computed for non-negative numbers in real numbers, while complex numbers require specialized handling. While Java provides the sqrt function to calculate square roots, you might want to know how to find the square root in Java without sqrt.
In this guide, you’ll discover both methods and learn how to apply them efficiently. By the end, you’ll understand the different approaches and improve your Java programming skills.
Improve your Java programming skills with our Software Development courses — take the next step in your learning journey!
In simple terms, the square root of a number is a value that, when multiplied by itself, gives the original number. For example, the square root of 25 is 5, because 5 * 5 = 25. Mathematically, the square root is represented as √n, where "n" is the number you want to find the square root of.
How Java Handles Square Root Calculation
Java provides a built-in method Math.sqrt() to calculate the square root of a number. This function returns the square root of a positive number as a double value.
It’s a quick and easy way to get the square root, but what if you need to calculate it manually or avoid using sqrt()? In that case, there are other ways to approach the calculation, and you’ll learn some of those methods here.
Why Square Root Matters in Programming
Square roots are used in many areas of programming, from calculating distances in graphics and game development to solving problems in physics and data analysis. Knowing how to calculate a square root in Java- both with and without Math.sqrt()-is useful for optimizing performance and implementing custom algorithms.
Also Read: Exploring the 14 Key Advantages of Java: Why It Remains a Developer's Top Choice in 2025
Now that we've covered the basics, let's dive into the most straightforward way to calculate a square root in Java using Math.sqrt().
The Math.sqrt() method in Java is the easiest and most straightforward way to calculate the square root of a number. This method is part of the Math class, which provides a range of mathematical functions.
The beauty of Math.sqrt() is that it handles most of the work for you, returning the square root of any positive number you pass to it.
Syntax and Working of Math.sqrt()
double result = Math.sqrt(double number);
Math.sqrt() in Java returns NaN for negative numbers because it only supports real numbers. Handling negative square roots requires complex numbers or additional logic.
Let’s walk through a quick example of how to use Math.sqrt() in Java.
public class SquareRootExample {
public static void main(String[] args) {
double number = 25.0; // The number we want to find the square root of
double squareRoot = Math.sqrt(number); // Using Math.sqrt() to find the square root
System.out.println("The square root of " + number + " is " + squareRoot);
}
}
Output:
The square root of 25.0 is 5.0
Explanation:
While Math.sqrt() is handy, there are situations where you might want to calculate the square root in Java without sqrt(). In the next section, you’ll explore some of those methods, including step-by-step examples of how you can do this manually.
While Math.sqrt() is a quick and efficient way to find the square root, there are times when you may need to calculate the square root in Java without sqrt().
Understanding these alternative approaches can be useful, whether it's for more control over the calculation, optimizing performance, or working in environments without access to the built-in method.
Let’s dive into some practical ways to achieve this manually.
The exponentiation method leverages the mathematical property that the square root of a number x can be calculated by raising x to the power of 0.5 (which is the same as taking the square root).
This is a straightforward and efficient approach using the Math.pow() function in Java.
Code Example:
public class SquareRootExponentiation {
public static void main(String[] args) {
double number = 25.0; // Number to find square root of
double squareRoot = Math.pow(number, 0.5); // Using exponentiation to calculate square root
System.out.println("The square root of " + number + " is " + squareRoot);
}
}
Output:
The square root of 25.0 is 5.0
Explanation:
Edge Cases:
Notes:
Also Read: String Functions In Java | Java String [With Examples]
Newton's Method, also known as the Babylonian Method for square roots, is an iterative algorithm to approximate the square root. It starts with an initial guess and improves it by repeatedly applying a formula until the result is sufficiently close to the true square root.
Formula:
The formula for updating the guess is:
Where x_old is the current guess, and n is the number for which we want to find the square root.
Code Example:
public class SquareRootNewtonMethod {
public static double sqrt(double n) {
double guess = n / 2; // Initial guess
double epsilon = 1e-6; // Desired precision
while (Math.abs(guess * guess - n) > epsilon) {
guess = 0.5 * (guess + n / guess); // Updating guess using the formula
}
return guess;
}
public static void main(String[] args) {
double number = 25.0; // Number to find square root of
double squareRoot = sqrt(number); // Using Newton's method
System.out.println("The square root of " + number + " is " + squareRoot);
}
}
Output:
The square root of 25.0 is 5.0
Explanation:
Edge Cases:
Notes:
Also Read: Top 13 String Functions in Java | Java String [With Examples]
The binary search method calculates the square root by repeatedly narrowing down the range where the square root lies. This method works by checking the middle point of a range and adjusting the range based on whether the square of the midpoint is greater than or less than the number.
Approach:
Code Example:
public class SquareRootBinarySearch {
public static double sqrt(double n) {
double low = 0, high = n, mid = 0;
double epsilon = 1e-6; // Desired precision
while (high - low > epsilon) {
mid = (low + high) / 2; // Find the midpoint
if (mid * mid > n) {
high = mid; // Adjust the upper bound
} else {
low = mid; // Adjust the lower bound
}
}
return mid;
}
public static void main(String[] args) {
double number = 25.0; // Number to find square root of
double squareRoot = sqrt(number); // Using binary search method
System.out.println("The square root of " + number + " is " + squareRoot);
}
}
Output:
The square root of 25.0 is 5.0
Explanation:
Edge Cases:
Notes:
Also Read: Binary Search Algorithm: Function, Benefits, Time & Space Complexity
Another interesting approach for calculating the square root is using logarithms and exponentiation. The mathematical idea behind this method is that the square root of a number n can be calculated using the natural logarithm (ln(n)) and Euler’s number (e). The formula looks like this:
Where e is Euler’s number and ln(n) is the natural logarithm of n. Using this formula, we can compute the square root by applying the exponential and logarithmic functions available in Java.
Code Example:
public class SquareRootLogarithm {
public static double sqrt(double n) {
return Math.exp(0.5 * Math.log(n)); // Using log and exp to find the square root
}
public static void main(String[] args) {
double number = 25.0; // Number to find square root of
double squareRoot = sqrt(number); // Using logarithmic and exponential functions
System.out.println("The square root of " + number + " is " + squareRoot);
}
}
Output:
The square root of 25.0 is 5.0
Explanation:
Edge Cases:
Notes:
If you need a higher degree of precision than what double can offer, Java’s BigDecimal class can be used to compute square roots. BigDecimal supports arbitrary precision, making it ideal for handling large numbers or numbers requiring high precision. This method involves an iterative approach similar to Newton’s Method but with the added benefit of greater accuracy.
Code Example:
import java.math.BigDecimal;
import java.math.MathContext;
public class SquareRootBigDecimal {
public static BigDecimal sqrt(BigDecimal n, int scale) {
BigDecimal guess = n.divide(BigDecimal.valueOf(2), MathContext.DECIMAL64); // Initial guess
BigDecimal epsilon = BigDecimal.valueOf(1e-15); // Desired precision
while (guess.multiply(guess).subtract(n).abs().compareTo(epsilon) > 0) {
guess = guess.add(n.divide(guess, MathContext.DECIMAL64))
.divide(BigDecimal.valueOf(2), MathContext.DECIMAL64);
}
return guess.setScale(scale, BigDecimal.ROUND_HALF_UP); // Set scale for the result
}
public static void main(String[] args) {
BigDecimal number = new BigDecimal("25.0"); // Number to find square root of
int scale = 10; // Precision scale
BigDecimal squareRoot = sqrt(number, scale); // Using BigDecimal for high precision
System.out.println("The square root of " + number + " is " + squareRoot);
}
}
Output:
The square root of 25.0 is 5.0000000000
Explanation:
Edge Cases:
Notes:
Also Read: Abstract Class and Methods in Java: Key Concepts, Examples and Best Practices
The Taylor Series expansion is a method for approximating functions, and it can also be used to calculate square roots. This method involves expanding the square root function into an infinite series and using the first few terms to estimate the square root. The approximation for the square root of n can be expressed as:
Where x is an initial guess and n is the number we want the square root of. The idea is to improve the guess iteratively.
Code Example:
public class SquareRootApproximation {
public static double sqrt(double n) {
double guess = n / 2; // Initial guess
double epsilon = 1e-6; // Desired precision
while (Math.abs(guess * guess - n) > epsilon) {
guess = 0.5 * (guess + n / guess); // Update guess using the approximation formula
}
return guess;
}
public static void main(String[] args) {
double number = 25.0; // Number to find square root of
double squareRoot = sqrt(number); // Using Taylor series approximation
System.out.println("The square root of " + number + " is " + squareRoot);
}
}
Output:
The square root of 25.0 is 5.0
Explanation:
Edge Cases:
Notes:
Also Read: Perfect Number Program for Java
Now that we've explored different methods, let's see how Math.sqrt() stacks up against the manual calculations we just discussed.
Math.sqrt() is usually quicker and easier for most situations, but manual methods can give you more control and precision when you need it. Here's a breakdown of how they compare.
Method | Pros | Cons | Best Use Case |
Math.sqrt() | - Simple and easy to use - Efficient for most use cases - Built-in and reliable | - Limited precision for very large or small numbers - Returns NaN for negative numbers | - Quick calculations in most standard scenarios |
Exponentiation (x^0.5) | - Straightforward - Works with basic Math.pow() function | - Can lack precision for extreme values - Less readable for some | - Simple, quick calculations when precision is not critical |
Newton’s Method | - High precision - Converges quickly for most values | - Requires multiple iterations - More complex to implement | - When high precision is required or when working with large values |
Binary Search | - Efficient for large numbers - Guarantees convergence within a set range - Useful for non-floating point numbers | - Slower than other methods due to iterative checks - More complex to implement | - When precision is needed and performance is not a primary concern |
Logarithmic & Exponential | - Interesting and mathematical approach - Useful in certain applications | - Slightly more complex - Needs handling for negative numbers | - When you want to avoid traditional iteration-based methods |
BigDecimal | - Very high precision - Ideal for financial or scientific calculations - Slow but is the only one supporting arbitrary precision | - Slower than floating-point operations - More complex to use | - For extremely precise calculations, especially in finance or data analysis |
Taylor Series Expansion | - Fast for approximations - Simple iterative approach | - Can require several iterations for precision - Not always the most efficient | - When you need a quick approximation or are dealing with smaller numbers |
Performance Differences and Use Cases
Now that you’ve got the methods down, let’s talk about some common mistakes and how to steer clear of them.
When working with square roots in Java, there are a few common pitfalls you should watch out for. Understanding these mistakes will help you avoid frustrating bugs and ensure your code runs smoothly.
Example:
double number = -25.0;
double squareRoot = Math.sqrt(number); // This will return NaN
if (number < 0) {
System.out.println("Cannot calculate the square root of a negative number.");
} else {
System.out.println("Square root: " + squareRoot);
}
Example:
double result = Math.sqrt(-4.0);
if (Double.isNaN(result)) {
System.out.println("The result is not a valid number.");
} else {
System.out.println("Square root: " + result);
}
Example:
If using manual methods for calculating square roots in Java without sqrt(), ensure the result is close enough to the expected value: double number = 25.0;
double calculatedSqrt = sqrt(number);
System.out.println("Calculated square root: " + calculatedSqrt);
Example:
BigDecimal number = new BigDecimal("123456789123456789");
BigDecimal sqrtValue = sqrt(number, 10); // Custom method using BigDecimal
System.out.println("Square root with BigDecimal: " + sqrtValue);
Example:
double number = 25.0;
double epsilon = 1e-6; // Desired precision
double guess = number / 2;
// Loop should stop when the difference is smaller than epsilon
while (Math.abs(guess * guess - number) > epsilon) {
guess = 0.5 * (guess + number / guess);
}
System.out.println("Square root: " + guess);
Example:
double number = 0;
if (number < 0) {
System.out.println("Cannot compute square root for negative numbers.");
} else {
System.out.println("Square root: " + Math.sqrt(number));
}
Example:
With binary search, ensure that the precision is high enough to match your needs:double precision = 1e-6; // High precision needed
double result = sqrt(number, precision);
System.out.println("Calculated square root: " + result);
Now that we've covered the common errors, let's dive into some real-world scenarios where square root calculations come in handy.
Square root calculations are widely used in various fields like graphics, physics, and data analysis. Here are some practical applications where square roots play an important role:
Understanding square roots and their applications is crucial for Java developers, especially when working with scientific calculations, simulations, or data-driven applications. Mastering these concepts helps ensure that you can tackle a wide range of real-world problems efficiently.
Test your knowledge of square roots in Java with these questions! From basic concepts to more advanced applications, let’s see how well you know square root calculations in Java.
1. What is the main purpose of the Math.sqrt() method in Java?
A) To calculate the square of a number
B) To calculate the square root of a number
C) To raise a number to a power
D) To find the cube root of a number
2. What will the Math.sqrt() method return if you pass a negative number?
A) An exception
B) NaN (Not a Number)
C) Infinity
D) Zero
3. Which method can be used to calculate the square root manually in Java without sqrt()?
A) Exponentiation (x^0.5)
B) Adding the number multiple times
C) Subtraction
D) Using a logarithmic function
4. What is the initial guess for the square root in Newton's Method?
A) 0
B) The number itself
C) Half of the number
D) The square of the number
5. In the binary search method for calculating the square root, which of the following does NOT describe the approach?
A) Divide the range into halves
B) Narrow down the range based on the midpoint’s square
C) Continue adjusting the guess until the range difference is below a certain threshold
D) Recalculate the square root based on the previous result
6. Why is it important to check for negative numbers when calculating square roots in Java?
A) Negative numbers will throw a runtime error
B) Negative numbers will result in NaN when passed to Math.sqrt()
C) Negative numbers are impossible to calculate the square root of in real numbers
D) Negative numbers are treated as zero in square root calculations
7. Which of the following methods guarantees the highest precision when calculating the square root in Java?
A) Math.sqrt()
B) Exponentiation
C) BigDecimal
D) Newton's Method
8. How does using the BigDecimal class improve the calculation of square roots in Java?
A) It speeds up calculations significantly
B) It provides higher precision and handles very large or small numbers
C) It makes the square root calculations simpler
D) It is only used for whole numbers
9. What is the primary reason for using logarithmic and exponential functions to calculate the square root in Java?
A) To avoid iteration and recursion
B) To increase precision
C) To implement square root calculations without using loops
D) To implement mathematical models in data analysis
10. In what scenario would manually calculating the square root in Java be preferred over using Math.sqrt()?
A) When you want a faster computation
B) When you need more control over the precision of the result
C) When you are working with very small numbers only
D) When you want to avoid any built-in methods
You can further enhance your Java skills with upGrad, where you'll dive deeper into advanced Java concepts and explore real-world applications to strengthen your expertise.
upGrad’s courses provide expert training in advanced Java concepts, including efficient square root calculations, mathematical functions, and performance optimization. You’ll gain hands-on experience with methods like Math.sqrt(), manual square root calculations, and precision handling.
Understanding these methods helps optimize Java applications requiring mathematical precision, such as finance, physics, and graphics programming.
Below are some relevant upGrad courses:
You can also receive personalized career guidance with upGrad to help navigate your career path, or visit your nearest upGrad center to begin practical, hands-on training today!
Similar Reads:
A. Yes, you can use methods like Newton’s Method or binary search for large numbers to maintain precision, especially when square root in Java without sqrt is required.
A. For high precision, using BigDecimal or Newton’s Method will provide better control and more accurate results compared to Math.sqrt().
A. No, Math.sqrt() returns NaN for negative numbers. To handle negative inputs, you would need to work with complex numbers or check inputs before calculating the square root.
A. Calculating square root in Java without sqrt (e.g., using Newton’s Method or binary search) can be slower than using Math.sqrt(), but gives more control over precision and performance in specific applications.
A. The main limitations are performance concerns and potential complexity in implementation, especially for large datasets or real-time calculations. It’s often more practical to use Math.sqrt() unless precision or customization is required.
A. You can optimize square root calculations by choosing faster methods like binary search or adjusting precision with BigDecimal when necessary, depending on the use case.
A. Yes, square root in Java without sqrt can be applied in matrix operations, especially for calculating distances between vectors or performing geometric transformations, but more advanced methods may be needed for efficiency.
A. Math.sqrt() is faster and more efficient for general use, while manual methods like Newton’s Method are better for cases requiring more control over precision or specific algorithmic approaches.
A. You can handle large or small results by using BigDecimal for higher precision or adjusting the epsilon value in methods like Newton’s Method to ensure accurate approximations.
A. Logarithmic functions provide an alternative approach to calculating square roots, especially when you need to avoid iteration and handle large or complex datasets efficiently. It’s a useful tool when precision and performance are key.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.