Area of Rectangle Example in Java
Introduction
Area Of Rectangle is a classic Java console program that demonstrates the concept with complete source code and sample output. Calculation programs apply formulas to solve geometry, statistics and numeric problems.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
The area of the rectangle is the length multiplied by the width.
Formula
The area of a rectangle is written as,
A=l*b
where,
A=Area
l=length
b=breadthArea Of Rectangle Example Program
import java.util.Scanner;
class AreaOfRectangle{
static Scanner in = new Scanner(System.in);
public static void main(String args[]){
System.out.print("Enter the length: ");
int length = in.nextInt();
System.out.print("Enter the breadth: ");
int breadth = in.nextInt();
int area=length*breadth;
System.out.println( "The area of the rectangle is:"+area) ;
}
}Sample Output
Enter the length: 4
Enter the breadth: 6
The area of the rectangle is:24When to use
Use these formulas in homework tools, engineering calculators or anywhere repeated numeric computation is needed.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.util.Scanner;imports a class used later in the program. -
A
Scannerreads typed input from the keyboard (System.in). -
A
println/printcall writes text to the console — part of the sample output below. -
int length = in.nextInt();updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
int breadth = in.nextInt();updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below.