English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java Math Mathematical Methods
The Java Math sqrt() method returns the square root of the specified number.
The syntax of the sqrt() method is:
Math.sqrt(double num)
Note: sqrt() is a static method. Therefore, we can access this method using the class name.
num -The number to calculate the square root of
Returns the square root of the specified number
Returns NaN if the parameter is less than 0 or NaN
Note: This method always returns a positive number and rounds correctly.
class Main { public static void main(String[] args) { //Create a double variable double value1 = Double.POSITIVE_INFINITY; double value2 = 25.0; double value3 = -16; double value4 = 0.0; //Square root of infinity System.out.println(Math.sqrt(value1)); // Infinity //Square root of a positive number System.out.println(Math.sqrt(value2)); // 5.0 //Square root of a negative number System.out.println(Math.sqrt(value3)); // NaN //Square root of zero System.out.println(Math.sqrt(value4)); // 0.0 } }
In the above example, we used the Math.sqrt() method to calculate the square root of infinity, positive numbers, negative numbers, and zero.
Here, Double.POSITIVE_INFINITY is used to implement positive infinity in the program.
When we pass an int value to the sqrt() method, it automatically converts the int value to a double value.
int a = 36; Math.sqrt(a); // Return 6.0