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

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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:

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