Java Program to Check If Given Four Points Form a Square

bookmark

import java.io.*;
class Main
{
    public static void main(String [] args)
    {
            int x1 = 0;// x-cordinate of A
            int y1 = 0;// y-cordinate of A
            int x2 = 0;// x-cordinate of B
            int y2 = 1;// y-cordinate of B
            int x3 = 1;// x-cordinate of C
            int y3 = 1;// y-cordinate of C
            int x4 = 1;// x-cordinate of D
            int y4 = 0;// y-cordinate of D
            
            // distance formula using 2 point 2d fomula 
            double AB = Math.sqrt(((x2-x1)*(x2-x1)) + ((y2-y1)*(y2-y1)));
            double BC = Math.sqrt(((x3-x2)*(x3-x2)) + ((y3-y2)*(y3-y2)));
            double CD = Math.sqrt(((x4-x3)*(x4-x3)) + ((y4-y3)*(y4-y3)));
            double DA = Math.sqrt(((x4-x1)*(x4-x1)) + ((y4-y1)*(y4-y1)));
            double AC = Math.sqrt(((x3-x1)*(x3-x1)) + ((y3-y1)*(y3-y1)));
            double BD = Math.sqrt(((x4-x2)*(x4-x2)) + ((y4-y2)*(y4-y2)));
            
            // checking conditions
            if(AB==BC && BC==CD && CD==DA && AC==BD)
                System.out.println("Valid square");
            else
                System.out.println("Not a valid square");
    }
}

 


Output:

Valid square