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
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
How do you calculate the square root of a number in Java with precision and performance?
The simplest and most accurate way is to use Java’s Math.sqrt() method, which belongs to the built-in Math class. It returns the square root of a number as a double and handles both integers and floating-point values.
But that’s not all—Java also allows you to implement square root logic manually, useful in coding interviews or when you want full control over the method. You can even combine it with Math.pow() for variations.
In this blog, we’ll explore the square root program in Java using Math.sqrt(), its syntax, return types, time complexity, and variations. You’ll also learn how to calculate square roots without using built-in methods, and how Math.cbrt() or Math.pow() extend similar functionality.
The Math.sqrt in Javascript is specifically used for calculating the square root of a given number. It takes a single argument, which is the number for which you want to find the solution, and returns the square root as a double value. The method follows the standard mathematical convention of returning the positive square root.
Here's an example that demonstrates how to use the Math.sqrt() method:
double number = 25.0;
double squareRoot = Math.sqrt(number);
System.out.println("Square root of " + number + " is: " + squareRoot);
In this example, we calculate the square root of the number 25.0 using the Math.sqrt() method.
The result, 5.0, is then printed to the console.
When using the Math.sqrt() method in Java, it's essential to keep a few best practices in mind:
In addition to the Math.sqrt() method, Java provides other methods that can be useful for square root calculations. Let's take a look at two of these variants: Math.cbrt() and Math.pow().
The Math.cbrt() method calculates the cube root of a given number. It follows a similar syntax to the Math.sqrt() method, taking a single argument and returning the cube root as a double value. Here's an example:
double number = 27.0;
double cubeRoot = Math.cbrt(number);
System.out.println("Cube root of " + number + " is: " + cubeRoot);
In this example, we calculate the cube root of the number 27.0 using the Math.cbrt() method. The result, 3.0, is then printed to the console.
The Math.pow() method allows you to raise a number to a specific power. It takes two arguments: the base number and the exponent. The method returns the result of raising the base to the exponent as a double value. Here's an example:
double base = 2.0;
double exponent = 3.0;
double result = Math.pow(base, exponent);
System.out.println(base + " raised to the power of " + exponent + " is: " + result);
In this example, we raise the base number 2.0 to the power of 3.0 using the Math.pow() method. The result, 8.0, is then printed to the console.
In this section, we'll explore the usage of the Math.sqrt() method through a few examples:
Example 1: Calculating the Square Root of an Input
import java.util.Scanner;
public class SquareRootExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double number = scanner.nextDouble();
double squareRoot = Math.sqrt(number);
System.out.println("Square root of " + number + " is: " + squareRoot);
}
}
Example input: 16
Output:
Square root of 16.0 is: 4.0
The code prompts the user to enter a number. In this example, the input is 16. The Math.sqrt() function is then used to calculate the square root of the entered number, which is 4.
Example 2: Calculating Hypotenuse of a Right-Angled Triangle
double side1 = 3.0;
double side2 = 4.0;
double hypotenuse = Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2));
System.out.println("The hypotenuse of the triangle is: " + hypotenuse);
In this example, we calculate the hypotenuse of a right-angled triangle using the Pythagorean theorem.
Output:
We use the Math.pow() method to calculate the squares of the sides and then apply the Math.sqrt() method to find the square root of the sum of the squares.
The time complexity of the Math.sqrt() method in Java is typically considered to be constant or O(1). This means that the time it takes to calculate the square root does not depend on the size of the input or any other factors.
Internally, the Math.sqrt() method relies on hardware instruction or a highly optimized algorithm provided by the underlying system. This allows it to perform the square root calculation efficiently in a fixed time, regardless of the magnitude of the input number.
It's important to note that the actual implementation and performance of the Math.sqrt() method may vary across different Java runtime environments and hardware platforms. However, in general, you can expect the time complexity of the Math.sqrt() method to be constant, providing fast and reliable square root calculations in your Java programs.
If you want to calculate the square root of a number in Java without using the Math.sqrt() method, you can implement your own algorithm. One commonly used approach is Newton's method or Newton-Raphson method, which iteratively refines an initial guess to approach the square root of a number.
It's an iterative numerical method used to approximate the roots of a real-valued function. To compute the square root of a number n, we define:
f(x) = x^2 - n
Then, apply the Newton-Raphson update rule:
x_new = 1/2 [x+(n/x)]
You start with an initial guess (x = n) and keep improving it until the difference is very small.
Here's an example of how you can implement it:
public class SquareRootNewtonRaphson {
// Function to calculate square root using Newton-Raphson Method
public static double squareRoot(double number) {
// Initial guess (can be any positive number, usually number/2 or 1)
double guess = number;
// Precision level
double precision = 0.00001;
// Loop until the guess is close enough to the real square root
while (Math.abs(guess * guess - number) > precision) {
// Newton-Raphson formula to improve the guess
guess = (guess + number / guess) / 2;
}
return guess;
}
public static void main(String[] args) {
double number = 49;
double result = squareRoot(number);
System.out.printf("Square root of %.2f is approximately %.5f\n", number, result);
}
}
Output:
Square root of 49.00 is approximately 7.00000
The code uses Newton's method to iteratively improve the guess for the square root of a number until convergence is achieved and then returns the calculated square root.
The Math.sqrt() method in Java accepts a double type as its argument and returns a double type as the square root. However, if you want to calculate the square root of an integer and obtain an integer result, you can utilize the type-casting technique. Here's an example:
int number = 25;
int squareRoot = (int) Math.sqrt(number);
System.out.println("Square root of " + number + " is: " + squareRoot);
By casting the result to an int using (int), we obtain the integer value of the square root. The output will be:
The square root of 25 is: 5
It's important to note that when using type casting to obtain an integer square root, the fractional part of the actual square root is truncated. This means that the resulting integer may be slightly smaller than the actual square root.
To find the square root in Java, use the Math.sqrt() method. It accepts a double value and returns the square root as a double. For example, Math.sqrt(25) returns 5.0.
The Math.sqrt() method is part of Java’s Math class. It calculates the square root of a given number. If the input is negative, it returns NaN (Not a Number).
Yes, you can calculate the square root in Java without using Math.sqrt() by using methods like the Newton-Raphson algorithm or binary search, which manually approximate the root.
A basic square root program in Java takes user input, converts it to double, and uses Math.sqrt() to find and display the result. It’s commonly used for mathematical computations and interview questions.
The return type of Math.sqrt() in Java is double. Even if you pass an integer, the method always returns a double value, which may need to be cast or rounded depending on the use case.
Yes, Math.sqrt() can handle integers because Java automatically promotes them to double. For example, Math.sqrt(16) returns 4.0.
If you pass a negative number to Math.sqrt() in Java, it returns NaN (Not a Number). You should use checks before calling the method to avoid this or work with complex number libraries.
The time complexity of Math.sqrt() is constant—O(1)—because it’s implemented natively using optimized machine-level instructions.
You can use Math.pow(number, 0.5) as an alternative to Math.sqrt() in Java. Both return the same result, but Math.sqrt() is more readable and precise for square roots.
Yes, Java provides Math.cbrt() to find cube roots. While Math.sqrt() handles square roots, Math.cbrt() returns the cube root of a number, also as a double.
You can use Scanner to take input and then apply Math.sqrt() to the user-entered number. This approach is common in Java square root programs for beginners and user-driven applications.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
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.