Java Program to find area of rectangle

In this program let us create a Java program to print the area of rectangle.

Program

import java.util.Scanner;
public class AreaofRectangle {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the length:\t");
        int length = sc.nextInt();
        System.out.print("Enter the breadth:\t");
        int breadth = sc.nextInt();
        int area = length * breadth;
        System.out.println("Area of rectangle is:\t" + area);
    }
}

Let us understand the program by breaking into simple parts:

  1. public class AreaofSquare: Any Java program starts with a class, in this case the class name is AreaofSquare
  2. public static void main(String[] args): main is the entry point for any Java program.
  3. Scanner sc = new Scanner(System.in); : System.in 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). System.in corresponds to keyboard input or another input source specified by the host environment or user.
  4. int length = 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 length entered by the user is stored in the variable length.
  5. int breadth = 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 breadth entered by the user is stored in the variable breadth.
  6. int area = length * breadth; : Calculate the area of rectangle using length and breadth.
  7. System.out.println("Area of rectangle is:\t" + area); : System.out.println prints the area of square with user entered inputs.

Output

Enter the length:	12 
Enter the breadth:	9
Area of rectangle is:	108