Press "Enter" to skip to content

Java Distance between Two Points in XY Plane

If (x1, y1) and (x2, y2) are two points or coordinates in XP plane, then we can find the distance between them by following mathematical distance formula:

Equation for Distance between Two Points in XY Plane

This formula was made from Pythagoras triangle theorem.


Now let’s see how to find distance between two points in Java:
If (x1, y1) and (x2, y2) are two points or coordinates in XP plane, then following java console program shows the distance between them.

Java Program for Finding Distance between Two Points

import java.io.*;
class distance
{
   int x1,y1,x2,y2,difx,dify;
   double d;

void get() throws IOException
  {
     BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
     System.out.print("\n Enter the X part of first point : ");
     x1=Integer.parseInt(Br.readLine());
     System.out.print(" Enter the Y part of first point : ");
     y1=Integer.parseInt(Br.readLine());
     System.out.print("\n Enter the X part of second point : ");
     x2=Integer.parseInt(Br.readLine());
     System.out.print(" Enter the Y part of second point :  ");
     y2=Integer.parseInt(Br.readLine());
  }
void display()
  {   
    difx = (x2 - x1) * (x2 - x1);
    dify = (y2 - y1) * (y2 - y1);
    d = Math.sqrt(difx + dify);
    System.out.println("\n Distance between (" + x1 + "," + y1 + ") and (" + x2 + "," + y2 + ") is : " + d + " unit(s) " );
  }
 public static void main(String p[]) throws IOException
 {
   distance dis = new distance();
   dis.get();
   dis.display();
 }
}

Sample Output:      

Java Distance between Two Points in XY Plane

Enter the X part of first point : 1 
Enter the Y part of first point : 4 

Enter the X part of second point : 4 
Enter the Y part of second point : 0 

Distance between (1, 4) and (4, 0) is : 5.0 unit(s).

Java Distance between Two Points in XY Plane and output

Get more Java programs here

Be First to Comment

Leave a Reply