In this tutorial, we will write a program to find the distance between two given points in java. Before that, you should have knowledge of the following topic in Java.
Distance Formula:
The distance between two coordinates or points is calculated using the following formula.
First point: (x1, y1)
Second point: (x2, y2)
Distance (MN): √((x2 – x1)2 + (y2 -y1)2)
Here x1, y1 are the coordinates of the first point and x2, y2 are the coordinates of the second point. These points indicate the x-axis and y-axis values.
Example:
First Points: (4, 8)
Seecond Points: (12, 14)
Then distance between them √((12-4)2 + (14-8)2) = √(64 + 36) = √(100) = 10
Java Program to Find the Distance between Two Points
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int x1, x2, y1, y2, x, y;
double distance;
System.out.println("Enter first coordinates (x1, y1): ");
x1 = scan.nextInt();
y1 = scan.nextInt();
System.out.println("Enter second coordinates (x2, y2): ");
x2 = scan.nextInt();
y2 = scan.nextInt();
//calculation
x = x2 - x1;
y = y2 - y1;
distance = Math.sqrt(x * x + y * y);
System.out.println("Distance between the two coordinates: " + distance);
}
}
Output:
Enter first coordinates (x1, y1):
5
3
Enter second coordinates (x2, y2):
2
3
Distance between the two coordinates: 3.0