**Get started with Spring 5 and Spring Boot 2, through the ***Learn Spring* course:

*Learn Spring*course:

Last modified: June 7, 2022

In this quick tutorial, we'll learn to solve an algorithmic problem of checking whether the two given rectangles overlap.

We'll start by looking at the problem definition and then progressively build up a solution.

Finally, we'll implement it in Java.

Let's say we have two given rectangles – *r1* and *r2*. We need to check if there's at least one common point among* r1* and *r2*. If yes, it simply means that these two rectangles overlap.

Let's have a look at some examples:

If we notice the very last case, the rectangles *r1* and *r2* have no intersecting boundaries. Still, they're overlapping rectangles as every point in *r1* is also a point in *r2*.

To solve this problem, we should first start by defining a rectangle programmatically. **A rectangle can be easily represented by its bottom-left and top-right coordinates:**

```
public class Rectangle {
private Point bottomLeft;
private Point topRight;
//constructor, getters and setters
boolean isOverlapping(Rectangle other) {
...
}
}
```

where *Point* is a class representing a point* (x,y)* in space:

```
public class Point {
private int x;
private int y;
//constructor, getters and setters
}
```

We'll later define *isOverlapping(Rectangle other) *method in our *Rectangle* class to check if it overlaps with another given rectangle – *other*.

The two **given rectangles won't overlap if** either of the below conditions is true:

- One of the two rectangles is above the top edge of the other rectangle
- One of the two rectangles is on the left side of the left edge of the other rectangle

For all other cases, the two rectangles will overlap with each other. To convince ourselves, we can always draw out several examples.

Now that we understand the solution, let's implement our *isOverlapping()* method:

```
public boolean isOverlapping(Rectangle other) {
if (this.topRight.getY() < other.bottomLeft.getY()
|| this.bottomLeft.getY() > other.topRight.getY()) {
return false;
}
if (this.topRight.getX() < other.bottomLeft.getX()
|| this.bottomLeft.getX() > other.topRight.getX()) {
return false;
}
return true;
}
```

Our *isOverlapping()* method in *Rectangle* class returns *false* if one of the rectangles is either above or to the left side of the other, *true* otherwise.

To find out if one rectangle is above the other, we compare their *y-coordinates*. Likewise, we compare the *x-coordinates* to check if one rectangle is to the left of the other.

In this short article, we learned how to solve an algorithmic problem of finding whether the two given rectangles overlap with each other. It serves as a collision detection strategy for two rectangular objects.

As usual, the entire source code is available over on Github.

Follow the Java Category

Follow the Java category to get regular info about the new articles and tutorials we publish here.