Implement distance formula in java

In this post, we will see how to implement distance formula between two points in java.

Formula to find distance between two points ( x1, y1) and (x2 , y2) is

d= sqrt( (x2-x1)^2+ (y2 – y1)^2)

Here is simple program to calculate distance between two points in java.

package org.arpit.java2blog;

public class calculateDistanceMain {

public static void main(String[] args) {
calcualteDistanceMain cdm=new calcualteDistanceMain();
double x1 = 8;
double y1 = 5;
double x2 = 4;
double y2 = 8;

double distance = cdm.getDistanceBetweenPoints(x1, y1, x2, y2);
System.out.println("Distance : "+distance);

}

public double getDistanceBetweenPoints( double x1, double y1, double x2, double y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
}

Here we have used math.sqrt to calculate square root.
When you run above program, you will get below output:

Distance : 5.0

That’s about how to implement distance formula in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.