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:
-
Create a point with given
xandyvalues. -
Print the coordinates of the point.
-
Compare two points to check if they are equal.
Hints / Help Points:
-
Use private variables for
xandy. -
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:
-
Pointclass has private variablesxandy. -
The constructor sets the values when a point is created.
-
printCoordinates()prints the point in(x, y)format. -
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.