Java Math sqrt() Method
The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value.
Syntax:
public static double sqrt(double a)
Parameters:
The parameter ‘a’ represents the number whose square root is to be determined.
Return Value:
The sqrt() method returns the positive square root of ‘a’.
- It returns zero with same sign as argument, if the argument is positive or negative zero.
- It returns infinity with the same sign as the argument, if the argument is infinite.
- It returns NaN, if the argument is NaN or less than zero.
Example 1:
public class JavaMathSqrtExample1 { public static void main(String[] args) { double a=4.0; //returns the square root of a double value System.out.println("Square root of "+ a +" = "+Math.sqrt(a)); } }
Output:
Square root of 4.0 = 2.0
Example 2:
public class JavaMathSqrtExample2 { public static void main(String[] args) { double a=Double.NaN; //returns the squre root of a NaN value System.out.println("Square root of "+ a +" = "+Math.sqrt(a)); } }
Output:
Square root of NaN = NaN
Example 3:
public class JavaMathSqrtExample3 { public static void main(String[] args) { double a=-0.0; //returns a zero with the same sign as the argument ,if the argument is zero. System.out.println("Square root of "+ a +" = "+Math.sqrt(a)); } }
Output:
Square root of -0.0 = -0.0
Example 4:
public class JavaMathSqrtExample4 { public static void main(String[] args) { double a=-5/0.0; //returns NaN,if the argument is less than zero. System.out.println("Square root of "+ a +" = "+Math.sqrt(a)); } }
Output:
Square root of -Infinity = NaN
Example 5:
public class JavaMathSqrtExample5 { public static void main(String[] args) { double a=Double.POSITIVE_INFINITY; //returns Infinity,if the argument is Positive infinity. System.out.println("Square root of "+ a +" = "+Math.sqrt(a)); } }
Output:
Square root of Infinity = Infinity