Java Math.sqrt() method returns the square root of a given number. In this guide, we will discuss sqrt() method in detail with examples.
public class JavaExample { public static void main(String[] args) { double num = 9; System.out.println("Square root: "+Math.sqrt(num)); } }
Output:
Square root: 3.0
Syntax of Math.sqrt() method
Math.sqrt(16); //returns 4.0
sqrt() Description
public static double sqrt(double num): Returns the square root of the given number num
.
sqrt() Parameters
It takes a single parameter:
- num: A number whose square root to be determined.
sqrt() Return Values
- Returns a double value, which is a square root of the given number.
- If the passed number is less than zero or NaN (Not a number) then this method returns NaN.
- If the passed argument is positive infinity, it returns positive infinity as square root.
- If the passed argument is zero, it returns zero.
Example 1: Finding Square root of a given number
public class JavaExample { public static void main(String[] args) { double num = 25; System.out.println("Square root of 25 is: "+Math.sqrt(num)); } }
Output:
Example 2: Square root of negative number and NaN
public class JavaExample { public static void main(String[] args) { double num = -51.55; //negative number double num2 = 0.0/0; //NaN System.out.println("Square root of negative number: "+Math.sqrt(num)); System.out.println("Square root of NaN is: "+Math.sqrt(num2)); } }
Output:
Example 3: Square root of zero
public class JavaExample { public static void main(String[] args) { double num = 5.0/0; //Infinity double num2 = 0; //Zero System.out.println("Square root of Infinity: "+Math.sqrt(num)); System.out.println("Square root of Zero is: "+Math.sqrt(num2)); } }
Output: