Java Program to calculate the area of a square


January 8, 2023, Learn eTutorial
2006

How to calculate the area of a square?

A square is a shape that has 4 sides that are equal in length. The area of a square is calculated by using the formula A=a*a.  where a is the side length.

How to compute a square area using the Java program?

First, we have to declare the class ArSq. Create an object of the scanner class as sc and read the length of the square from the user into the variable s. Calculate the area as a=s*s. Finally, display the value in variable a.

ALGORITHM

STEP 1: Declare the class ArSq with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Read the side from the user into the variable s.

STEP 4: Calculate the area as a=s*s.

STEP 5: Display the area of the square a using System.out.println() method.

Java Source Code

                                          import java.util.Scanner;
public class ArSq
{
   public static void main(String args[]) 
   {   
       double a,s;
      Scanner sc = new Scanner(System.in);

      System.out.println("Enter the side of the square:");
      s = sc.nextDouble();

      a = s*s;
      System.out.println("Area of the square is: " + a);    
   }
}
                                      

OUTPUT

Enter the side of the square:10
Area of the square is: 100.0