Blog
Java Math.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
xandy.