View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Square Root in Java: Using Math.sqrt() and Other Methods

Updated on 25/06/20259,988 Views

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.

Math.sqrt() Method: Description and Examples

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.

Best Practices for Using the Math.sqrt() Method

When using the Math.sqrt() method in Java, it's essential to keep a few best practices in mind:

  • Ensure the input value is non-negative: The Math.sqrt() method can only calculate the square root of non-negative numbers. The method will return NaN (Not a Number) if you pass a negative value. Therefore, it's important to validate the input before invoking the method.
  • Handle edge cases: Consider scenarios where the input is zero or very close to zero. The Math.sqrt() method may not always return an exact zero due to the limitations of floating-point arithmetic. It's crucial to handle such cases in your code and make appropriate adjustments if necessary.
  • Be mindful of the precision: The Math.sqrt() method returns a double value, which has limited precision. If you require a higher accuracy or need to work with arbitrary precision, consider alternative approaches like using specialized libraries or implementing your own algorithms.

Math.sqrt() Method Variations

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().

Math.cbrt()

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.

Math.pow() in Java

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.

Java sqrt() Method with Examples

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.

math.sqrt java time complexity

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.

Square root in Java without sqrt

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.

Newton-Raphson Method

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.

Math.sqrt Java int

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.

FAQs

1. How do you find the square root in Java?

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.

2. What is Math.sqrt() in Java?

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).

3. Can I find square root without using Math.sqrt() in Java?

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.

4. How to write a square root program in Java?

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.

5. What is the return type of Math.sqrt() in Java?

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.

6. Can Math.sqrt() handle integer inputs in Java?

Yes, Math.sqrt() can handle integers because Java automatically promotes them to double. For example, Math.sqrt(16) returns 4.0.

7. How to handle negative numbers with Math.sqrt() in Java?

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.

8. What is the time complexity of Math.sqrt() in Java?

The time complexity of Math.sqrt() is constant—O(1)—because it’s implemented natively using optimized machine-level instructions.

9. How does Math.pow() help in finding square roots?

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.

10. Can I find the cube root using Java Math functions?

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.

11. How to find the square root of any number in Java using Scanner?

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.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Pavan Vadapalli

Author|900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.