Java Program to find perimeter of rectangle

In this program let us create a Java program to calculate and print the perimeter of rectangle.


import java.util.Scanner;
public class PerimeterofRectangle {
    public static void main(String args[]) {
        Scanner sc = new Scanner(;
        System.out.print("Enter the width:\t");
        int width = sc.nextInt();
        System.out.print("Enter the height:\t");
        int height = sc.nextInt();
        int perimeter = 2 * (width + height);
        System.out.println("Perimeter of rectangle is:\t" + perimeter);

Let us understand the program by breaking into simple parts:

  1. public class PerimeterofRectangle: Any Java program starts with a class, in this case the class name is PerimeterofRectangle
  2. public static void main(String[] args): main is the entry point for any Java program.
  3. Scanner sc = new Scanner(; : is passed as a parameter in Scanner class. This creates an object of Scanner class which is defined in java. util. scanner package. Scanner class tells the java compiler that system input will be provided through console(keyboard). corresponds to keyboard input or another input source specified by the host environment or user.
  4. int width = sc.nextInt(); : The nextInt() method of Java Scanner class is used to scan the next token of the input as an int. The value of width entered by the user is stored in the variable width.
  5. int height = sc.nextInt(); : The value of height entered by the user is stored in the variable height.
  6. int perimeter = 2 * (width + height); : Calculate the perimeter of rectangle using the value of width and height given by the user.
  7. System.out.println("Perimeter of rectangle is:\t" + perimeter); : System.out.println prints the perimeter of rectangle with user entered inputs.


Enter the width:	20
Enter the height:	12
Perimeter of rectangle is:	64