# Distance between two points java – Java Program to Calculate Distance Between Two Points

Distance between two points java: In the previous article, we have seen Java Program to Calculate Average of N Numbers

In this article we will see how we can find distance between two points using Java programming language.

## Java Program to Calculate Distance Between Two Points

Distance formula java: Suppose we have two points i.e. point A(x1,y1) and point B(x2,y2). So, by using these coordinates of 2 points we will find the distance between the two points.

Formula to find distance between two points = sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))

Let’s see different ways to find distance between two points.

### Method-1: Java Program to Calculate Distance Between Two Points By Using Static Input Value

Approach:

• Declare the coordinates of two points with its value.
• Then find the distance between the two points using the formula.

Program:

class Main
{
public static void main(String arg[])
{
//double variable 'distance' declared
double distance;
//coordinates with it's value declared
int x1=3, y1=5, x2=6, y2=7;
//finding distance between two points
distance=Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
//printing distance
System.out.println("Distance between two points"+ distance);
}
}
Output:

Distance between two points 3.605551275463989

### Method-2: Java Program to Calculate Distance Between Two Points By Using User Input Value

Approach:

• Declare the coordinates of two points and take the value as user input.
• Then find the distance between the two points using the formula.

Program:

import java.util.*;

class Main
{
public static void main(String arg[])
{
//Scanner class object created
Scanner sc=new Scanner(System.in);
//double variable 'distance' declared
double distance;
//coordinates value taking input from user
System.out.println("Enter x1 value: ");
int x1=sc.nextInt();
System.out.println("Enter y1 value: ");
int y1=sc.nextInt();
System.out.println("Enter x2 value: ");
int x2=sc.nextInt();
System.out.println("Enter y2 value: ");
int y2=sc.nextInt();
//finding distance between two points
distance=Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
//printing distance
System.out.println("Distance between two points "+ distance);
}
}
Output:

Enter x1 value:
3
Enter y1 value:
4
Enter x2 value:
6
Enter y2 value:
7
Distance between two points 4.242640687119285

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Related Java Programs: