Distance Between Two Points in Java

Distance between two points in Java | Distance formula Java | Program description:- Write a Java program to find the distance between two given points.

The distance formula is derived from the Pythagorean theorem. To find the distance between two points (x1, y1) and (x2, y2), all that you need to do is use the coordinates of these ordered pairs and apply the formula.

Distance Formula Java

Assume we have two points M and N, with coordinates (x1, y1) and (x2, y2) respectively. Their distance  can be represented as MN and it can be calculated as given below formula,

The first point (M):- (x1, y1)
Second point (N):- (x2, y2)
Distance (MN):- √((x2 – x1)2 + (y2 -y1)2)

Example:-
M = (4, 8)
N = (12, 14)
Then distance between M and N is, MN = √((12-4)2 + (14-8)2) = √(64 + 36) = √(100) = 10

Distance Between Two Points in Java

import java.util.Scanner;
public class Distance {
  public static void main(String[] args) {

    // create Scanner class object
    // to read input values
    Scanner scan = new Scanner(System.in);

    // declare variables
    int x1, x2, y1, y2, x, y;
    double distance;

    // read points coordinates
    System.out.print("Enter first point coordinates: ");
    x1 = scan.nextInt();
    y1 = scan.nextInt();
    System.out.print("Enter second point 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 them = " + distance);
  }
}

Output for the different test-cases:-

Enter first point coordinates: 4 8
Enter second point coordinates: 12 14
Distance between them = 10.0

Enter first point coordinates: 0 0
Enter second point coordinates: 5 12
Distance between them = 13.0

Enter first point coordinates: -5 0
Enter second point coordinates: 12 8
Distance between them = 18.788294228055936

To find the square root value we are using sqrt() method of java.lang.Math class. To find the power value we can also use Math.pow() method but we have used a simple multiplication operator.

In this program, to read input values we have used the Scanner class. The result can be floating-point value therefore we had taken the distance variable as double data type variable, remaining all other variables are of the int data type.

We had taken input values and calculated the distance between X coordinate points, and later we calculated the distance between Y co0rdinates of both points. Finally, we had used the distance formula to find the distance between two given points and displayed it on the screen. 

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *