What is the correct way to calculate the distance between two points using the Java distance formula, and how can I fix my current implementation?

I’m building a program to determine if two circles overlap. I’ve gathered all the user input and calculated the combined radii, but I’m having trouble calculating the distance between the centers of the circles.

Eclipse keeps telling me that distance should be resolved to an array, even though I declared it as an int.

Here’s the line causing the issue:

distance = Math.sqrt((x1-x2)(x1-x2) + (y1-y2)(y1-y2));

I’m trying to apply the Java distance formula between two points ((x1, y1)) and ((x2, y2)), but clearly I’ve got a syntax or type error. What’s the correct way to do this in Java, and how should I fix this line?

Here’s your original code:

distance = Math.sqrt((x1-x2)(x1-x2) + (y1-y2)(y1-y2));

The issue? In Java, you can’t multiply like this: (x1 - x2)(x1 - x2) — it’s not algebra.

You need to use the * operator explicitly.

Also, Math.sqrt returns a double, not an int.

Here’s the corrected version:

double distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));

If you really need it as an int (say, for comparison), cast it like this:

int distance = (int) Math.sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));

Another cleaner and more readable way — especially when you’re new to Java math operations is to use Math.pow():

double distance = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));

This approach makes it obvious that you’re squaring the differences. And it’s especially useful if you’re going to reuse this logic or teach it to someone.

To keep your main logic clean and reusable, extract the distance formula into a method:

public static double getDistance(int x1, int y1, int x2, int y2) {
    return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
}

Then call it like this:

double distance = getDistance(x1, y1, x2, y2);