π Java Program to Calculate Area of a Rectangle β With Examples
π§² Introduction
Calculating the area of a rectangle is one of the simplest and most common geometric operations in Java. Whether you’re building a geometry calculator, GUI layout system, or floor planner, this logic is essential.
By the end of this article, you’ll learn:
- β How to compute the area of a rectangle in Java
- β
Take user input using
Scanner
- β Write clean and reusable Java methods
π’ Formula for Area of Rectangle
Area = Length Γ Breadth
Both values must be positive numbers, typically in int
or double
format.
π» Java Program β Hardcoded Input
public class RectangleArea {
public static void main(String[] args) {
int length = 10;
int breadth = 5;
int area = length * breadth;
System.out.println("Area of rectangle = " + area);
}
}
β Explanation:
length
andbreadth
are initialized directly.area = length * breadth
applies the rectangle area formula.- Output is printed with
System.out.println
.
π₯ Java Program β User Input with Scanner
import java.util.Scanner;
public class RectangleAreaInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter length: ");
double length = scanner.nextDouble();
System.out.print("Enter breadth: ");
double breadth = scanner.nextDouble();
double area = length * breadth;
System.out.println("Area of rectangle = " + area);
}
}
β Explanation:
Scanner
readsdouble
input from user.- Calculates area using multiplication.
- Works for both integers and decimal inputs.
π‘ Always close the Scanner
using scanner.close()
in production code.
π Java Method β Reusable Function
public class RectangleUtils {
public static double calculateArea(double length, double breadth) {
return length * breadth;
}
public static void main(String[] args) {
double area = calculateArea(8.5, 4.2);
System.out.println("Area = " + area);
}
}
β Explanation:
calculateArea()
is a reusable method.- Keeps code modular and clean.
β οΈ Edge Case Warning
if (length <= 0 || breadth <= 0) {
System.out.println("Length and breadth must be positive.");
return;
}
β οΈ Always validate input values to avoid incorrect or negative area calculations.
π Example Output
Enter length: 6
Enter breadth: 3
Area of rectangle = 18.0
π Summary
In this article, youβve learned:
- β How to calculate rectangle area in Java using formula
- β
Take user input with
Scanner
- β Use methods for clean and reusable logic
This knowledge applies to many Java-based geometry, GUI, and simulation projects.
β FAQ β Area of Rectangle in Java
βCan I use float
instead of double
?
Yes, but double
is preferred for higher precision.
βHow do I handle invalid input?
Use exception handling:
try {
double length = scanner.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter a number.");
}
Share Now :