askvity

How to get sqrt in Java?

Published in Java Math Function 2 mins read

To get the square root in Java, you use the Math.sqrt() method.

Using Math.sqrt()

The Math.sqrt() method is a built-in function in the Java Math class that calculates the square root of a number. Here's how to use it:

  • Method Signature: public static double sqrt(double a)
  • Parameter: The method accepts a single parameter, a, which is a double value.
  • Return Value: The method returns the square root of the parameter a as a double value.
    • If a is a positive number, the method returns its square root.
    • If a is NaN (Not a Number) or less than zero, the method returns NaN, according to the reference.

Example

public class SqrtExample {
    public static void main(String[] args) {
        double number = 25.0;
        double squareRoot = Math.sqrt(number);
        System.out.println("The square root of " + number + " is: " + squareRoot); // Output: 5.0

        double negativeNumber = -10.0;
        double sqrtOfNegative = Math.sqrt(negativeNumber);
        System.out.println("The square root of " + negativeNumber + " is: " + sqrtOfNegative); // Output: NaN

       double nanValue = Double.NaN;
        double sqrtOfNan = Math.sqrt(nanValue);
        System.out.println("The square root of NaN is: " + sqrtOfNan); // Output: NaN
    }
}

Key Points

  • The Math.sqrt() method only accepts double values as input. If you are dealing with integers, you may need to cast them to double before using this method.
  • The method returns NaN if the input is negative or NaN. You might want to include error handling to check for this case.
  • The return value is always a double type.

Summary

Function Description Input Type Return Type Special Cases
Math.sqrt(x) Computes the square root of the given number double double Returns NaN if x is NaN or less than zero

Related Articles