Java hypot() Method
Java Math.hypot() Method
In Java, the hypot()
method is part of the java.lang.Math
class. It is used to calculate the hypotenuse of a right-angled triangle, given the lengths of the other two sides.
โ Method Signature
public static double hypot(double x, double y)
The Math.hypot(x, y)
method returns sqrt(xยฒ + yยฒ)
without intermediate overflow or underflow, which makes it more accurate than manually computing the square root of x*x + y*y
.
๐ Parameters
x
โ one side of the triangle.y
โ the other side of the triangle.
๐ฏ Returns
The length of the hypotenuse as a double
.
๐งฎ Example
public class HypotExample {
public static void main(String[] args) {
double a = 3.0;
double b = 4.0;
double hypotenuse = Math.hypot(a, b);
System.out.println("Hypotenuse is: " + hypotenuse); // Output: 5.0
}
}
๐ฏ Use Case
Useful in:
- Geometry calculations
- Game development (e.g., distance between two points)
- Scientific applications
โ ๏ธ Note
- Using
Math.hypot()
is better thanMath.sqrt(x*x + y*y)
because: - It avoids overflow and underflow.
- It’s more accurate for large or very small values of
x
andy
.