Pin It

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 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 object
  Scanner scanner = new Scanner(;

  // 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 :

Please Give Us Your 1 Minute In Sharing This Post!
Related Posts Plugin for WordPress, Blogger...
© 2012 Learn Java by Examples Template by Hubber Spot