Java Program to Calculate Distance between Two Points - The Coding Shala

Home >> Java Programs >> Calculate Distance between Two Points

 In this post, we will learn how to find Distance between two points using Java Program.

Java Program to Calculate Distance between Two Points

You have given two points with coordinates (x1, y1) and (x2, y2). Write a Java program to find the distance between these two points.

We can find the distance between two points using the distance formula.

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

Example 1:
Input: (x1,y1) = (3,4)
           (x2, y2) = (7, 7)
Output: 5

Java Program: 

// Java program to find distance between two points

import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) { 
		Scanner sc = new Scanner(System.in);
		
		int x1, y1, x2, y2;
		
		// take inputs
		System.out.println("Enter x1: ");
		x1 = sc.nextInt();
		System.out.println("Enter y1: ");
		y1 = sc.nextInt();
		
		System.out.println("Enter x2: ");
		x2 = sc.nextInt();
		System.out.println("Enter y2: ");
		y2 = sc.nextInt();
		
		// find distance using distance formula
		double distance = Math.sqrt(((x2-x1) * (x2-x1)) + ((y2-y1) * (y2-y1)));
		System.out.println("Distance between (" + x1 + "," + y1 + ") and (" + x2 + "," + y2 + ") => " + distance);
		
		sc.close();
	}

}

Output: 

Enter x1: 
3
Enter y1: 
4
Enter x2: 
7
Enter y2: 
7
Distance between (3,4) and (7,7) => 5.0


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala

Java Program to Reverse a String using Stack - The Coding Shala