Point Distance Calculator in Java: Explanation & Practice

Calculate distance between two points

Problem summary

Create a Point class that calculates distance to another point.

Starter code

// Create Point class with:
// - double x, y
// - double distanceTo(Point other)
// Distance formula: sqrt((x2-x1)^2 + (y2-y1)^2)

public class Main {
    public static void main(String[] args) {
        // Test case 1: (0,0) to (3,4)
        // Print: Distance: <result>
    }
}

Expected output and test cases

  • 3-4-5 triangle
    Distance: 5.0
  • Same point
    Distance: 0.0
  • Diagonal unit
    Distance: 1.41

Hints

  1. Use Math.sqrt() for square root
  2. Use Math.pow() for squaring
  3. Distance formula from geometry

Related OOP Basics exercises

Practice all OOP Basics exercises · Run this idea in the Java compiler