How to check if a point is inside a rectangle in Java

3 Answers

0 votes
public class PointInRectangle {

    static class Point {
        double x, y;

        Point(double x, double y) {
            this.x = x;
            this.y = y;
        }
    }

    static class Rectangle {
        Point topLeft;
        Point bottomRight;

        Rectangle(Point topLeft, Point bottomRight) {
            this.topLeft = topLeft;
            this.bottomRight = bottomRight;
        }
    }

    public static boolean isPointInsideRectangle(Point p, Rectangle rect) {
        return p.x >= rect.topLeft.x && p.x <= rect.bottomRight.x &&
               p.y >= rect.topLeft.y && p.y <= rect.bottomRight.y;
    }

    public static void main(String[] args) {
        Rectangle rect = new Rectangle(new Point(0.0, 0.0), new Point(7.0, 7.0));
        Point p = new Point(3.0, 2.0);

        if (isPointInsideRectangle(p, rect)) {
            System.out.println("The point is inside the rectangle.");
        } else {
            System.out.println("The point is outside the rectangle.");
        }
    }
}


 
/*
run:
 
The point is inside the rectangle.
 
*/

 



answered Jun 22, 2025 by avibootz
0 votes
import java.awt.Rectangle;

public class PointInRectangle {
    public static void main(String[] args) {
        // Define the rectangle
        Rectangle rectangle = new Rectangle(10, 10, 60, 60); // x=10, y=10, width=60, height=60

        // Define the point
        int pointX = 30;
        int pointY = 20;

        // Check if the point is inside the rectangle
        boolean isInside = rectangle.contains(pointX, pointY);

        if (isInside) {
            System.out.println("The point (" + pointX + ", " + pointY + ") is inside the rectangle.");
        } else {
            System.out.println("The point (" + pointX + ", " + pointY + ") is outside the rectangle.");
        }
    }
}


 
/*
run:
 
The point (30, 20) is inside the rectangle.
 
*/

 



answered Jun 22, 2025 by avibootz
0 votes
import java.awt.geom.Rectangle2D;

public class PointInRectangle {
    public static void main(String[] args) {
        // Define the rectangle
        Rectangle2D rectangle = new Rectangle2D.Double(10, 10, 60, 50); // x, y, width, height

        // Define the point
        double pointX = 30;
        double pointY = 20;

        // Check if the point is inside the rectangle
        boolean isInside = rectangle.contains(pointX, pointY);

        // Output the result
        if (isInside) {
            System.out.println("The point (" + pointX + ", " + pointY + ") is inside the rectangle.");
        } else {
            System.out.println("The point (" + pointX + ", " + pointY + ") is outside the rectangle.");
        }
    }
}


 
/*
run:
 
The point (30.0, 20.0) is inside the rectangle.
 
*/

 



answered Jun 22, 2025 by avibootz
...