Java program to find area and perimeter of square

Let’s learn java program to find area and perimeter of square.

Java program to find area and perimeter of square

Find perimeter and area of square is one of the common java interview question. In the below java program first user enters side of square using nextInt() method of Scanner class.

This value is stored in integer variable ‘side’. In the next step perimeter is calculated using below formula.

perimeter = 4 * side

Finally perimeter of a square is printed on console. Let’s see java program to find perimeter of square.

import java.util.Scanner;
public class SquarePerimeter
{
   public static void main(String[] args)
   {
      int side, perimeter;
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter side length of square: ");
      side = sc.nextInt();
      perimeter = 4 * side;
      System.out.print("Perimeter of square is: " + perimeter);
      sc.close();
   }
}


Output:

Please enter side length of square: 6
Perimeter of square is: 24


Now let’s learn to find area of square. So to find area of square first user enters side of square using nextDouble() method of Scanner class.

This user entered number is stored in double variable ‘side’. Now to find area of square the formula is Area = side * side.

Finally print the area of square on console. Here’s the java program to find area of square.

import java.util.Scanner;
public class FindAreaOfSquare
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter side of square: ");
      double side = sc.nextDouble();
      // formula area of square = side * side
      double area = side * side;
      System.out.println("Area of square is: " + area);
      sc.close();
   }
}


Output:

Please enter side of square: 5
Area of square is: 25.0


Also read – major features of java