Date: 2015nov17
Update: 2025oct8
Language: Java
Keywords: overlap, collision, union, ontop, inside
Q. Java: Test if 2 rectangles intersect
A. The Java class java.awt.Rectangle has a method for this.
So if are using it you can just call intersects()
but not you can adapt the code as shown in a full example:
import java.awt.Rectangle;
class Demo {
public static boolean intersects(final Rectangle a, final Rectangle b) {
final int neww = (a.x + a.width < b.x + b.width ?
a.x + a.width : b.x + b.width) - (a.x < b.x ? b.x : a.x);
final int newh = (a.y + a.height < b.y + b.height ?
a.y + a.height : b.y + b.height) - (a.y < b.y ? b.y : a.y);
return (neww > 0 && newh > 0);
}
public static final void main(String []args) {
{ // Test 1
final int x = 10, y = 10, width = 100, height = 100;
Rectangle r1 = new Rectangle(x, y, width, height);
Rectangle r2 = new Rectangle(x + 5, y + 5, width, height);
boolean result = intersects(r1, r2);
System.out.println("intersects=" + result + " (true is expected)");
}
{ // Test 2
final int x = 10, y = 10, width = 10, height = 10;
Rectangle r1 = new Rectangle(x, y, width, height);
Rectangle r2 = new Rectangle(x + 20, y + 20, width, height);
boolean result = intersects(r1, r2);
System.out.println("intersects=" + result + " (false is expected)");
}
}
}
Output:
intersects=true (true is expected)
intersects=false (false is expected)