Java Program to Find if Two Rectangles Overlap

bookmark

import java.util.Scanner;
public class Main
{
    // Class to store the coordinates
    static class Coordinate
    {
        int x,y;
    }
    public static void main(String[] args)
    {
        // Declaring the variables
        Coordinate l1 = new Coordinate(),
        r1 = new Coordinate(),
        l2 = new Coordinate(),
        r2 = new Coordinate();
        // Initializing the variables with the rectangles coordinates
        l1.x=0;
        l1.y=20;
        r1.x=20;
        r1.y=0;
        l2.x=5;
        l2.y=5;
        r2.x=15;
        r2.y=0;
        if(overlapCheck(l1,r1,l2,r2))
            System.out.println("The rectangles overlap");
        else
            System.out.println("The rectangles do not overlap");
    }
    // Checks whether the rectangles overlap on each other
    public static boolean overlapCheck(Coordinate l1, Coordinate r1, Coordinate l2, Coordinate r2)
    {
        // Checks for first condition -
        // One rectangle is on left side of the other
        if(l1.x>r1.x||l2.x>r2.x)
            return false;
        // Checks for second condition -
        // One rectangle is above the other
        if(l1.y<r1.y||l2.y<r2.y)
            return false;
        
        return true;
    }
}

 


Output:

The rectangles overlap