Java Math sqrt() example

In this guide, you will learn about the Math sqrt() method in Java programming and how to use it with an example.

1. Math sqrt() Method Overview

Definition:

The sqrt() method of Java's Math class is used to calculate the square root of a given number.

Syntax:

Math.sqrt(double a)

Parameters:

- a: The value whose square root needs to be computed.

Key Points:

- If the argument a is NaN or less than zero, then the result will be NaN.

- If the argument a is positive infinity, then the result will be positive infinity.

- If argument a is zero, then the result will be zero.

- It returns the positive square root of a double value.

2. Math sqrt() Method Example

public class SqrtExample {
    public static void main(String[] args) {
        System.out.println("Square root of 16: " + Math.sqrt(16));
        System.out.println("Square root of 0: " + Math.sqrt(0));
        System.out.println("Square root of 7: " + Math.sqrt(7));
        System.out.println("Square root of 2.25: " + Math.sqrt(2.25));
        System.out.println("Square root of -9 (will result in NaN): " + Math.sqrt(-9));
    }
}

Output:

Square root of 16: 4.0
Square root of 0: 0.0
Square root of 7: 2.6457513110645907
Square root of 2.25: 1.5
Square root of -9 (will result in NaN): NaN

Explanation:

In the example:

1. The square root of 16 is 4.

2. The square root of 0 is 0.

3. The square root of 7 is approximately 2.6457513110645907.

4. The square root of 2.25 is 1.5.

5. Since we can't compute the square root of a negative number using this method, it results in NaN (Not a Number).

Related Java Math class method examples

Comments