Professional Documents
Culture Documents
Java Math Hypot
Java Math Hypot
hypot() – Examples
Java Math hypot()
hypot() computes the length of hypotenuse, given base and height as arguments.
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.
Java Program
MathExample.java
public class
MathExample {
public static void
main(String[] args) {
doubleclass
public baseMathExample
= 3; {
double height = 4;
publichypotenuse
double static void =
main(String[] args) {
Math.hypot(base,
double base = 3;
height);
double height = 4;
System.out.println(hyp
double hypotenuse = Math.hypot(base, height);
otenuse);
} System.out.println(hypotenuse);
}
}
}
Output
Console Output
5.0
5.0
Example – 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
MathExample.java
public class
MathExample {
public static void
main(String[] args) {
float base
public class =MathExample
3.0F; {
int height = 4;
publichypotenuse
double static void =
main(String[] args) {
Math.hypot(base,
float base = 3.0F;
height);
int height = 4;
System.out.println(hyp
double hypotenuse = Math.hypot(base, height);
otenuse);
} System.out.println(hypotenuse);
}
}
}
Output
Console Output
5.0
5.0
Java Program
MathExample.java
public class
MathExample {
public static void
main(String[] args) {
double base =
Double.POSITIVE_INFIN
ITY;
double height = 4;
double hypotenuse =
Math.hypot(base,
height);
System.out.println(hyp
otenuse);
}
}
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
Console Output
Infinity
Infinity
Java Program
MathExample.java
public class
MathExample {
public static void
main(String[] args) {
doubleclass
public baseMathExample
= 3.0; {
double height =
public static void main(String[] args) {
Double.NaN;
double hypotenuse
double base = =3.0;
Math.hypot(base,
double height = Double.NaN;
height);
double hypotenuse = Math.hypot(base, height);
System.out.println(hyp
otenuse);
System.out.println(hypotenuse);
}
} }
}
Output
Console Output
NaN
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.
Java Tutorial
⊩ Java Tutorial
⊩ Java Math