Java Tutorial Java Advanced Java References

Java Math - sqrt() Method



The Java sqrt() method returns the square root of the given number. In special cases it returns the following:

  • If the argument is NaN or less than zero, then the result is NaN.
  • If the argument is positive infinity, then the result is positive infinity.
  • If the argument is positive zero or negative zero, then the result is the same as the argument.

Syntax

public static double sqrt(double arg)

Parameters

arg Specify a number.

Return Value

Returns the square root of the specified number.

Exception

NA.

Example:

In the example below, sqrt() method is used to find out the square root of the given number.

public class MyClass {
 public static void main(String[] args) {
  System.out.println(Math.sqrt(25)); 
  System.out.println(Math.sqrt(30)); 
  System.out.println(Math.sqrt(35.5)); 
  System.out.println(Math.sqrt(-25));     
 }
}

The output of the above code will be:

5.0
5.477225575051661
5.958187643906492
NaN

❮ Java Math Methods

5