In this tutorial, you will learn how to calculate the area and perimeter of a rectangle in Java. We will cover four different approaches:
- Basic approach (hardcoded values)
- User input (using the Scanner class)
- Modular approach (using user-defined methods)
- Object-Oriented Programming (OOP) (classes and encapsulation)
Let’s explore each method step by step with code examples. Before starting to write a Java program to find the area and perimeter of a rectangle, we will first understand the formulas of them.
Area and Perimeter of a Rectangle
A rectangle has two pairs of equal opposite sides. To calculate its area and perimeter, we need two dimensions:
- Length
- Breadth (or width)
Formula for Area of a Rectangle
The formula for the area of a rectangle is:
- Area = Length × Breadth
For example, if:
- Length = 10
- Breadth = 5
Then:
Area = 10 × 5 = 50 square units
The area represents the amount of two-dimensional space inside the rectangle.
Formula for Perimeter of a Rectangle
The formula for the perimeter of a rectangle is:
- Perimeter = 2 × (Length + Breadth)
For example, if:
- Length = 10
- Breadth = 5
Then:
- Perimeter = 2 × (10 + 5) = 30 units
The perimeter represents the total distance around the boundary of the rectangle.
Basic Approach to Find Area and Perimeter of a Rectangle in Java
Write a Java program to calculate the area and perimeter of a rectangle without taking input from the user and display both results on the console.
The program takes the length and breadth (width) of a rectangle as input and calculates its area and perimeter using standard mathematical formulas.
This is the basic approach, which requires only basic input, variables, multiplication, and output, making it suitable for a beginner learning Java. It calculates the values directly inside the main() method using fixed (hardcoded) variables.
Complete Java Program to Calculate Area and Perimeter of Rectangle
The following Java program uses fixed values for the length and breadth. It calculates and displays both the area and perimeter.
/**
* Program to calculate the Area and Perimeter of a Rectangle
* using the basic approach (hardcoded values).
*/
public class RectangleBasic {
public static void main(String[] args) {
// 1. Declare and initialize the dimensions of the rectangle
double length = 10.0;
double breadth = 5.0;
// 2. Compute the area using the formula: Area = Length * Breadth
double area = length * breadth;
// 3. Compute the perimeter using the formula: Perimeter = 2 * (Length + Breadth)
double perimeter = 2 * (length + breadth);
// 4. Print the rectangle dimensions and computed results to the console
System.out.println("--- Rectangle Details ---");
System.out.println("Length: " + length);
System.out.println("Breadth: " + breadth);
System.out.println("Area of Rectangle: " + area);
System.out.println("Perimeter of Rectangle: " + perimeter);
}
}Expected Output:
--- Rectangle Details --- Length: 10.0 Breadth: 5.0 Area of Rectangle: 50.0 Perimeter of Rectangle: 30.0
Explanation of Program Code
Let’s understand the program code step by step.
Step 1: Declare the Length and Breadth
double length = 10.0; double breadth = 5.0;
Here, we have declared two variables named length and breadth using the double data type and initialized with values. The double type allows the program to work with both whole numbers and decimal values. For example:
double length = 10.5; double breadth = 4.5;
This makes the program more flexible than using only int variables.
Step 2: Calculate the Area of the Rectangle
double area = length * breadth;
The multiplication operator (*) computes the area, and then the result is stored in a variable named area.
Step 3: Calculate the Perimeter of a Rectangle
double perimeter = 2 * (length + breadth);
The + operator first adds the length and breadth, and then the result is multiplied by 2. After calculation, the result is stored in a variable named perimeter.
Step 4: Display the Results
System.out.println("Area of Rectangle: " + area);
System.out.println("Perimeter of Rectangle: " + perimeter);The System.out.println() method displays the calculated values on the console.
Java Program to Find Area and Perimeter of Rectangle Using Scanner
In the previous program, we have directly assigned values to the variables length and breadth. Now, we will accept the dimensions, such as length and breadth, from the user at runtime. For this purpose, we use Java’s Scanner class.
Complete Java Program
// Import Scanner class from java.util package for user input
import java.util.Scanner;
/**
* Program to calculate the Area and Perimeter of a Rectangle
* dynamically using standard console input (Scanner).
*/
public class RectangleScanner {
public static void main(String[] args) {
// 1. Initialize Scanner object to capture standard input stream (System.in)
Scanner scanner = new Scanner(System.in);
// 2. Prompt the user and read floating-point values for length and breadth
System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("Enter the breadth of the rectangle: ");
double breadth = scanner.nextDouble();
// 3. Compute the area using the formula: Area = Length * Breadth
double area = length * breadth;
// 4. Compute the perimeter using the formula: Perimeter = 2 * (Length + Breadth)
double perimeter = 2 * (length + breadth);
// 5. Display the calculated results to the console
System.out.println("Area of Rectangle: " + area);
System.out.println("Perimeter of Rectangle: " + perimeter);
// 6. Close the scanner to release underlying system resources
scanner.close();
}
}Expected Output:
Enter the length of the rectangle: 12.5 Enter the breadth of the rectangle: 4.0 Area of Rectangle: 50.0 Perimeter of Rectangle: 33.0
In this program code:
- The statement
import java.util.Scanner;imports the utility Scanner class needed to read primitive types from various input streams, including standard keyboard input. - The
Scanner scanner = new Scanner(System.in);instantiates a Scanner object bound to System.in (the standard input stream). - The scanner.nextDouble() method scans the next token of the input as a double, allowing the program to accept decimal dimensions.
- The calculation logic computes the area and perimeter of a rectangle.
- The scanner.close() method explicitly closes the stream scanner to prevent resource leaks.
Calculate Area and Perimeter of Rectangle Using User-Defined Method
Instead of placing all calculation logic inside the main() method, we can create separate methods for calculating the area and perimeter of a rectangle. This approach makes the calculation logic reusable.
Complete Java Program
/**
* Program to calculate the Area and Perimeter of a Rectangle
* using user-defined static methods (modular/procedural approach).
*/
public class RectangleMethods {
/**
* Calculates the area of a rectangle.
* @param length The length of the rectangle.
* @param breadth The breadth (width) of the rectangle.
* @return The product of length and breadth as a double.
*/
public static double calculateArea(double length, double breadth) {
return length * breadth;
}
/**
* Calculates the perimeter of a rectangle.
* @param length The length of the rectangle.
* @param breadth The breadth (width) of the rectangle.
* @return The perimeter 2 * (length + breadth) as a double.
*/
public static double calculatePerimeter(double length, double breadth) {
return 2 * (length + breadth);
}
public static void main(String[] args) {
// 1. Declare and initialize the rectangle dimensions
double length = 12.0;
double breadth = 8.0;
// 2. Call user-defined methods and capture the returned values
double area = calculateArea(length, breadth);
double perimeter = calculatePerimeter(length, breadth);
// 3. Display the input dimensions and computed values
System.out.println("--- Rectangle Dimensions & Results ---");
System.out.println("Length: " + length);
System.out.println("Breadth: " + breadth);
System.out.println("Area: " + area);
System.out.println("Perimeter: " + perimeter);
}
}Expected Output:
--- Rectangle Dimensions & Results --- Length: 12.0 Breadth: 8.0 Area: 96.0 Perimeter: 40.0
In this program code:
- Instead of writing the computation logic directly in the main method, we have separated formulas into independent, reusable functions (calculateArea and calculatePerimeter).
- The public static modifier ensures that we can access methods from outside the class if needed.
- The static modifier allows the method to be invoked directly by name from main without creating an instance/object of the RectangleMethods class.
- The return statement passes a numeric floating-point result back to the caller.
- The main method passes the values of length and breadth as arguments into calculateArea(length, breadth) and calculatePerimeter(length, breadth), which execute and return 96.0 and 40.0, respectively.
Java Program to Calculate Area and Perimeter of a Rectangle Using OOP
In this section, you will learn how to find the area and perimeter of a rectangle using object-oriented programming (OOP) in Java. It is a clean, organized way to write Java programs and introduces core concepts like classes, objects, constructors, and encapsulation.
Complete Java Program
/**
* Class representing a Rectangle entity.
* Demonstrates Encapsulation by bundling state (fields) and behavior (methods).
*/
class Rectangle {
// 1. Private fields (data hiding) to restrict direct external access
private double length;
private double breadth;
/**
* Parameterized Constructor to initialize Rectangle dimensions.
* @param length The length of the rectangle.
* @param breadth The breadth of the rectangle.
*/
public Rectangle(double length, double breadth) {
this.length = length;
this.breadth = breadth;
}
/**
* Calculates the area of the current rectangle instance.
* @return The calculated area (length * breadth).
*/
public double getArea() {
return this.length * this.breadth;
}
/**
* Calculates the perimeter of the current rectangle instance.
* @return The calculated perimeter 2 * (length + breadth).
*/
public double getPerimeter() {
return 2 * (this.length + this.breadth);
}
// Getters for inspecting internal state
public double getLength() {
return length;
}
public double getBreadth() {
return breadth;
}
}
/**
* Driver class to instantiate and test the Rectangle object.
*/
public class RectangleOOP {
public static void main(String[] args) {
// 2. Instantiate a Rectangle object with specific dimensions
Rectangle rect = new Rectangle(15.0, 7.0);
// 3. Access object state via getters
System.out.println("--- Rectangle (OOP) Details ---");
System.out.println("Length: " + rect.getLength());
System.out.println("Breadth: " + rect.getBreadth());
// 4. Invoke instance methods to compute and print results
System.out.println("Area: " + rect.getArea());
System.out.println("Perimeter: " + rect.getPerimeter());
}
}Expected Output:
--- Rectangle (OOP) Details --- Length: 15.0 Breadth: 7.0 Area: 105.0 Perimeter: 44.0
In this program code:
- Encapsulation: The fields length and breadth are declared private, preventing direct modification from outside the class and protecting data integrity.
- Constructor: The Rectangle(double length, double breadth) constructor sets the initial state of the object upon creation using the new keyword.
- this Keyword: Resolves ambiguity between the constructor parameters and the instance variables (this.length refers to the class field).
- Instance Methods: getArea() and getPerimeter() operate directly on the internal fields of the specific object instance (rect), eliminating the need to pass arguments during method calls.
Important Points to Remember
When writing a Java program to find the area and perimeter of a rectangle, remember these points:
- A rectangle requires two dimensions: length and breadth/width.
- The area formula is
length * breadth. - The perimeter formula is
2 * (length + breadth). - Use
doublewhen decimal dimensions should be supported. - Use
Scanner.nextDouble()when accepting decimal values from the keyboard. - Use
intwhen the problem specifically requires integer dimensions.



