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 adouble
value. - Return Value: The method returns the square root of the parameter
a
as adouble
value.- If
a
is a positive number, the method returns its square root. - If
a
isNaN
(Not a Number) or less than zero, the method returnsNaN
, according to the reference.
- If
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 acceptsdouble
values as input. If you are dealing with integers, you may need to cast them todouble
before using this method. - The method returns
NaN
if the input is negative orNaN
. 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 |