java.lang.Math.hypot(double x, double y)

Description

On this document we will be showing a java example on how to use the hypot(double x, double y) method of Math Class. The hypot() method returns the sqrt(x2 + y2). I will save you on complicated explanation, it is simply a method to get the hypotenuse of a triangle. This is helpful in a scenario where we are dealing with right triangle and we only knew the base and height. The following special cases must be noted:

  • If either argument is infinite, then the result is positive infinity.
  • If either argument is NaN and neither argument is infinite, then the result is NaN.

Most of the methods of the Math class is static and the hypot() method is no exception. Thus don’t forget that in order to call this method, you don’t have to create a new object rather use the method in the format Math.copySign(magnitude, sign).

Method Syntax

public static double hypot(double x, double y)

Method Returns

The hypot() method returns sqrt(x2 + y2) without intermediate overflow or underflow

Compatibility

Requires Java 1.5 and up

Java Math hypot() Example

Below is a java code demonstrates the use of hypot() method of Math class. The example presented might be simple however it shows the behavior of the hypot() method.

package com.javatutorialhq.java.examples;

import java.util.Scanner;

/*
 * This example source code demonstrates the use of  
 * hypot() method of Math class.
 * 
 */

public class MathHypotExample {

	public static void main(String[] args) {
		
		// Ask for triangle height
		System.out.print("Enter the height of a triangle:");
		
		// use scanner to read the console input
		Scanner scan = new Scanner(System.in);
		
		// Assign the height input to String variable
		String height = scan.nextLine();
		
		// Ask for triangle base
		System.out.print("Enter the base of a triangle:");
		
		// Assign the base input to String variable
		String base = scan.nextLine();
		
		// close the scanner object
		scan.close();		
		
		// convert the values to double
		double doubleHeight = Double.parseDouble(height);
		double doubleBase = Double.parseDouble(base);		
			
		// get the result of copySign method
		double hypotenuse = Math.hypot(doubleHeight, doubleBase);
		System.out.print("Hypotenuse of the trianle:"+hypotenuse);
	}

}

The above java example source code demonstrates the use of hypot() method of Math class. We simply ask for two user input and we use the Scanner class to parse it. Since we have used the nextLine() method to get the console value which is having a return data type of String thus we have used the Double.parseDouble() to transform it into double. The two inputs corresponds to the base and height of a triangle. The result of the hypot() method returns the hypotenuse of a right triangle with the base and height given.

Sample Output

Below is the sample output when you run the above example.

java lang Math hypot() example output