askvity

How to use math sqrt in Java?

Published in Java Math Functions 3 mins read

To calculate the square root of a number in Java, you use the Math.sqrt() method. This method is part of the Math class in the java.lang package, which means you don't need to import anything to use it. Here's a comprehensive guide:

Understanding Math.sqrt()

The Math.sqrt() method takes a double value as input and returns the square root of that value, also as a double.

Syntax

double squareRoot = Math.sqrt(number);

Example

Here’s a simple example demonstrating how to use Math.sqrt():

public class SquareRootExample {
    public static void main(String[] args) {
        double number = 25.0;
        double squareRoot = Math.sqrt(number);
        System.out.println("The square root of " + number + " is " + squareRoot); // Output: The square root of 25.0 is 5.0
    }
}

Using Math.sqrt() with Different Data Types

While Math.sqrt() accepts a double and returns a double, you might want to calculate the square root of an integer. Here's how you can do it:

Example with Integers

public class SquareRootIntegerExample {
    public static void main(String[] args) {
        int number = 25;
        double squareRoot = Math.sqrt(number); // Implicit conversion from int to double
        System.out.println("The square root of " + number + " is " + squareRoot); // Output: The square root of 25 is 5.0

        // If you need an integer result:
        int squareRootInt = (int) Math.sqrt(number); // Casting the double result to int
        System.out.println("The integer square root of " + number + " is " + squareRootInt); // Output: The integer square root of 25 is 5
    }
}

Important Note about Casting

When casting the result of Math.sqrt() to an int, you are essentially truncating the decimal part. This means you're only getting the integer part of the square root. Be mindful of this when you need precise results.

Practical Applications of Math.sqrt()

Math.sqrt() is useful in various mathematical and engineering calculations. Here are a few examples:

  • Calculating Hypotenuse: Given the lengths of two sides of a right-angled triangle, you can use Math.sqrt() to calculate the length of the hypotenuse, as shown in reference (4), using the Pythagorean theorem (a² + b² = c²).
  • Distance Calculation: In graphics and game development, you can use Math.sqrt() to calculate the distance between two points in a 2D or 3D space.

Example: Calculating Hypotenuse

public class HypotenuseExample {
    public static void main(String[] args) {
        double side1 = 3.0;
        double side2 = 4.0;
        double hypotenuse = Math.sqrt(side1 * side1 + side2 * side2);
        System.out.println("The hypotenuse is: " + hypotenuse); // Output: The hypotenuse is: 5.0
    }
}

Summary Table

Method Description Input Type Return Type Example
Math.sqrt() Calculates the square root of a number. double double Math.sqrt(25.0) returns 5.0

Related Articles