Distance between two points in java

2 methods to calculate distance between two points in java with code example. 1- Using formula. 2- Using a Point class objects.

Distance between two points using formula

We know that the distance between two points (x1,y1) and (x2,y2) on a flat surface is as below. That we’ll use in the java program to find distance.

    ____________________
   /       2          2
 \/ (y2-y1)  + (x2-x1)

Code Example:

This is very simple java program to demonstrate how we can calculate the distance between two co-ordinates / points using formula.

/*--------------------------------------------------------
 * Simple example to get distance between two points
 * (x1,y1) and (x2,y2)
 */

public class Sample {

	public static void main(String[] args) {

		// point 1
		double x1 = 1;
		double y1 = 1;

		// point 2
		double x2 = 5;
		double y2 = 5;

		// Calculate distance between two points
		double distance = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1)
				* (y2 - y1));

		System.out.println("Distance between two points :" + distance);
	}

}

Distance between two points using Point Class

This program has a class Point with fields X and Y. We will create two objects of it representing two points.

It contains a method “double getDistance(Point p)” that returns distance between two points.

Code Example:

/*---------------------------------------------------------
 * Example to calculate distance between two points objects.
 */
class Point {

	private double x;
	private double y;

	Point(double x, double y) {
		this.x = x;
		this.y = y;
	}

	public double getX() {
		return x;
	}

	public double getY() {
		return y;
	}

	// This method accept a point object
	// and calculate distance with current object.

	// "this" keyword refer current object.
	public double getDistance(Point p) {

		return Math.sqrt((this.getX() - p.getX()) * (this.getX() - p.getX())
				+ (this.getY() - p.getY()) * (this.getY() - p.getY()));
	}

}

public class Sample {

	public static void main(String[] args) {

		Point px = new Point(1, 1);

		Point py = new Point(5, 5);

		double distance = px.getDistance(py);

		System.out.println(distance);
	}

}

Related Posts