Java Program to Check Whether a Given Point Lies Inside a Rectangle or Not
public class Main
{
// Driver code
public static void main (String[] args)
{
//Rectangle Coordinate A(10,10), B(10,-10), C(-10,-10), D(-10,-10)
//Point P(0,0)
//Calling the checkPoint() method
if (checkPoint(10, 10, 10, -10, -10, -10, -10, 10, 0, 0))
System.out.print("Point lies inside rectangle");
else
System.out.print("Point does not lie inside rectangle");
}
//Method to calculate the area of triangle
static float area(int x1, int y1, int x2,
int y2, int x3, int y3)
{
return (float)Math.abs((x1 * (y2 - y3) +
x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);
}
//Method to check whether point P(x, y)
//lies inside rectangle ABCD or not.
static boolean checkPoint(int x1, int y1, int x2, int y2,
int x3, int y3, int x4, int y4, int x, int y)
{
// Find area of rectangle ABCD
float Area = area(x1, y1, x2, y2, x3, y3)+
area(x1, y1, x4, y4, x3, y3);
// Calculate area of triangle PAB
float Area1 = area(x, y, x1, y1, x2, y2);
// Calculate area of triangle PBC
float Area2 = area(x, y, x2, y2, x3, y3);
// Calculate area of triangle PCD
float Area3 = area(x, y, x3, y3, x4, y4);
// Calculate area of triangle PAD
float Area4 = area(x, y, x1, y1, x4, y4);
// Checking if sum of Area1, Area2, Area3 and Area4
// is same with Area or not
//Returns true if Area == Area1 + Area2 + Area3 + Area4
// else returns false
return (Area == Area1 + Area2 + Area3 + Area4);
}
}
Output:
Point lies inside rectangle
