Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to Calculate Area and Perimeter of Rectangle in a Java Program

Program to demonstrate how to Calculate Area and Perimeter of Rectangle in Java.



 

package com.hubberspot.example;

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

public class RectangleAreaPerimeterDemo {

 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 length, breadth , area and perimeter of Rectangle.
  int length = 0;
  int breadth = 0;
  int area = 0;
  int perimeter = 0;

  // prompt the user to enter value of length of
  // Rectangle 
  System.out.print("Enter the length of Rectangle : ");

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

  // prompt the user to enter value of breadth of
  // Rectangle
  System.out.print("Enter the breadth of Rectangle : ");

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

  // Calculate area of Rectangle by multiplying length into breadth.
  area = length * breadth;

  // Calculate perimeter of Rectangle by 2 * (length + breadth)
  perimeter = 2 * (length + breadth);

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


Output of the program : 


 
 
© 2021 Learn Java by Examples Template by Hubberspot