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
xandy.