Java Math hypot()

hypot() computes the length of hypotenuse, given base and height as arguments.

Following is the syntax of hypot() method.

double hypotenuse = hypot(double base, double height)

Since the definition of hypot() function has double datatype for arguments, you can pass int, float or long as arguments as these datatypes will implicitly promote to double.

Example 1 – Math.hypot(double, double)

In the following example, we pass base and height as arguments to hypot() method and find the length of hypotenuse.

Java Program

public class MathExample {
	public static void main(String[] args) {
		double base = 3;
		double height = 4;
		double hypotenuse = Math.hypot(base, height);
		System.out.println(hypotenuse);
	}
}

Output

5.0
ADVERTISEMENT

Example 2 – Math.hypot(float, int)

In the following example, we pass base (of float datatype) and height (of int datatype) as arguments to hypot() method and find the length of hypotenuse.

Java Program

public class MathExample {
	public static void main(String[] args) {
		float base = 3.0F;
		int height = 4;
		double hypotenuse = Math.hypot(base, height);
		System.out.println(hypotenuse);
	}
}

Output

5.0

Example 3 – Math.hypot(base, height) – Infinite Base or Height

If any of the base or height is infinite, then the length of hypotenuse is infinite, and hypot() returns positive infinite.

Java Program

public class MathExample {
	public static void main(String[] args) {
		double base = Double.POSITIVE_INFINITY;
		double height = 4;
		double hypotenuse = Math.hypot(base, height);
		System.out.println(hypotenuse);
	}
}

Output

Infinity

Example 4 – Math.hypot(base, height) – NaN Base or Height

If any of the base or height, or both, is NaN, then hypot() returns NaN.

Java Program

public class MathExample {
	public static void main(String[] args) {
		double base = 3.0;
		double height = Double.NaN;
		double hypotenuse = Math.hypot(base, height);
		System.out.println(hypotenuse);
	}
}

Output

NaN

Note: Preference would be given to Infinity, and then to NaN. So, if there is Infinity value for base or height, irrespective of the other value being NaN, then the output is infinity.

Conclusion

In this Java Tutorial, we learned about Java Math.hypot() function, with example programs.