0
0
JavaHow-ToBeginner · 3 min read

How to Use Math.sqrt in Java: Simple Square Root Calculation

In Java, you use Math.sqrt to find the square root of a number by passing a double value as an argument. It returns the square root as a double. For example, Math.sqrt(9) returns 3.0.
📐

Syntax

The Math.sqrt method takes one argument, a double value, and returns its square root as a double. The argument must be non-negative; otherwise, the result will be NaN (Not a Number).

  • Math.sqrt(value): Calculates the square root of value.
  • value: A double number to find the square root of.
  • Returns a double representing the square root.
java
double result = Math.sqrt(25);
💻

Example

This example shows how to use Math.sqrt to calculate the square root of different numbers and print the results.

java
public class SquareRootExample {
    public static void main(String[] args) {
        double number1 = 16;
        double number2 = 2.25;
        double number3 = 0;

        System.out.println("Square root of " + number1 + " is " + Math.sqrt(number1));
        System.out.println("Square root of " + number2 + " is " + Math.sqrt(number2));
        System.out.println("Square root of " + number3 + " is " + Math.sqrt(number3));
    }
}
Output
Square root of 16.0 is 4.0 Square root of 2.25 is 1.5 Square root of 0.0 is 0.0
⚠️

Common Pitfalls

Common mistakes when using Math.sqrt include:

  • Passing a negative number, which returns NaN because square root of negative numbers is not defined for real numbers.
  • Using integer types without converting to double, which can cause unexpected results due to integer division.

Always ensure the input is non-negative and preferably a double.

java
public class SqrtPitfall {
    public static void main(String[] args) {
        double negative = -4;
        System.out.println("Square root of -4: " + Math.sqrt(negative)); // Outputs NaN

        int intValue = 9;
        // Works fine because int is promoted to double
        System.out.println("Square root of 9: " + Math.sqrt(intValue));
    }
}
Output
Square root of -4: NaN Square root of 9: 3.0
📊

Quick Reference

Remember these quick tips when using Math.sqrt:

  • Input must be a non-negative number.
  • Returns a double value.
  • Negative inputs return NaN.
  • Works with integers as they are converted to double.

Key Takeaways

Use Math.sqrt to calculate the square root of a non-negative double value.
Passing a negative number to Math.sqrt returns NaN, not an error.
Math.sqrt always returns a double, even if input is an integer.
Ensure input is non-negative to avoid unexpected NaN results.
You can directly pass integer values; they are converted to double automatically.