How to calculate Area and Perimeter of Square in Java ?.


Program to demonstrate how to calculate Area and Perimeter of Square in Java




 

package com.hubberspot.example;

// Import java.util.Scanner to read data from 
// console
import java.util.Scanner;

public class SquareAreaPerimterDemo {

 public static void main(String[] args) {

  // Creating a Scanner object using a constructor
  // which takes the System.in object. There are various 
  // constructors for Scanner class for different
  // purposes. We want to use Scanner class to read
  // data from console on the system, So we are using 
  // a constructor which is taking an System.in object
  Scanner scanner = new Scanner(System.in);

  // Create three variables which will hold the
  // values for side, area and perimeter of square
  int side = 0;  
  int area = 0;
  int perimeter = 0;

  // prompt the user to enter value of length of side of 
  // square
  System.out.println("Enter the length of side of square ");

  // store the side length into side variable entered by user
  side = scanner.nextInt();

  // Calculate area of square by multiplying side into side
  area = side * side;
  // Calculate perimeter of square by multiplying 4 into side
  perimeter = 4 * side;

  // Output area and perimeter to the console
  System.out.println("Area of Square is : " + area);
  System.out.println("Perimeter of Square is : " + perimeter);
 }
}



Output of the program :