In this tutorial you will learn about the Java Program to Find Distance Between 2 Points and its application with practical example.
In this tutorial, we will learn to create a Java Program to Find Distance between 2 point using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
Distance Between two Points
Using Pythagorean theorem to find the distance between two points (x1, y1) and (x2, y2), all we need are the coordinates in pairs and apply the formula.
Distance Formula:
Distance:- √((x2 – x1)2 + (y2 -y1)2).
Assume :=> We have two points A and B, with coordinates (x1, y1) and (x2, y2) respectively. So their distance can be represented as AB and it can be calculated as.
The first point (A):- (x1, y1)
Second point (B):- (x2, y2)
Java Program to Find Distance Between 2 Points
In this our program we will create a program to find Distance Between two points. We would first declared and initialized the required variables. Next, we would prompt user to input value.Later in the program we will find Distance between points.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// java program to find distance between two places. import java.util.Scanner; public class Distance { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // declaring variables int x1, x2, y1, y2, x, y; double distance; // Taking value from user of cordinates.. System.out.print("Enter first coordinates: "); x1 = scan.nextInt(); y1 = scan.nextInt(); System.out.print("Enter second coordinates: "); x2 = scan.nextInt(); y2 = scan.nextInt(); // calculate the distance between them x = x2-x1; y = y2-y1; distance = Math.sqrt(x*x + y*y); // display result System.out.println("Distance between two Point is = " + distance); } } |
Output
In the above program, we have first declared and initialized a set variables required in the program.
- x1 = it will hold value of first coordinates
- y1 = it will hold value of first coordinates
- x2 = it will hold value of second coordinates
- y2 = it will hold value of second coordinates
- x= it will represent distance.
- y= it will represent distance.
- distance= it will display final result.
the Formula to find the distance between two points is:
To calculate the distance between two points “(x1,y1) and (x2,y2) or √ ( x )2+( y )2“ . All you need is use the coordinates formula shown below.
Here we will to use following formula “ Math.sqrt(x*x+y*y))” and Math.sqrt() function which is define in Java standard library.it will take two parameter as a arguments x and y values supply to it.And in return gives the required output.
As shown in image above.