Table of Contents

    Java Program to Implement a 2D Point Class with Printing and Equality Check

    Question: Java Program to Represent a 2D Point

    Task:
    Write a Java class to represent a 2D point with coordinates (x, y). Your class should be able to:

    1. Create a point with given x and y values.

    2. Print the coordinates of the point.

    3. Compare two points to check if they are equal.

    Hints / Help Points:

    • Use private variables for x and y.

    • Create a constructor to assign values to the point.

    • Create a method printCoordinates() to display the point like (x, y).

    • Create a method equals(Point other) to compare two points.

    • Optional: Override equals(Object obj) if you want it to work with Java collections.

    Example Usage:

    
    Point p1 = new Point(3, 4);
    Point p2 = new Point(3, 4);
    
    p1.printCoordinates();           // Output: (3, 4)
    System.out.println(p1.equals(p2)); // Output: true
    
    

    Solution:

    
    // Class to represent a 2D Point
    class Point {
        private int x; // x-coordinate
        private int y; // y-coordinate
    
        // Constructor to initialize the point
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    
        // Method to print coordinates
        public void printCoordinates() {
            System.out.println("(" + x + ", " + y + ")");
        }
    
        // Method to compare two points
        public boolean equals(Point other) {
            return this.x == other.x && this.y == other.y;
        }
    }
    
    // Test class
    public class TestPoint {
        public static void main(String[] args) {
            Point p1 = new Point(3, 4);
            Point p2 = new Point(3, 4);
            Point p3 = new Point(5, 6);
    
            // Print points
            p1.printCoordinates(); // Output: (3, 4)
            p3.printCoordinates(); // Output: (5, 6)
    
            // Compare points
            System.out.println(p1.equals(p2)); // true
            System.out.println(p1.equals(p3)); // false
        }
    }
    
    

    Explanation:

    1. Point class has private variables x and y.

    2. The constructor sets the values when a point is created.

    3. printCoordinates() prints the point in (x, y) format.

    4. equals(Point other) checks if another point has the same coordinates.

    ✅ This solution is simple, easy to understand, and works perfectly for Class 11 students.