Calculate Perimeter of Rectangle in Java
beginner· Basics & I/O · Geometry
Problem
A rectangle's perimeter is the total distance around it — twice the length plus twice the width, since opposite sides are equal.
Given the length and width of a rectangle, calculate its perimeter.
Input
length = 10.0, width = 5.0
Output
Perimeter: 30.0
Java Program
Java
public class CalculatePerimeterOfRectangle {
public static void main(String[] args) {
double length = 10.0;
double width = 5.0;
double perimeter = 2 * (length + width); // twice the sum of length and width
System.out.println("Perimeter: " + perimeter);
}
}Output
Perimeter: 30.0
Core Logic
Adding length and width, then doubling the sum, gives the perimeter directly, in a single expression.
How It Works
- 1
lengthholds10.0andwidthholds5.0. - 2
2 * (length + width)evaluates to30.0. - 3The parentheses ensure length and width are added together before doubling, matching the geometric meaning.
- 4The result is stored in
perimeterand printed with a label.
For
length = 10.0 and width = 5.0, 2 * (10.0 + 5.0) gives 30.0.💡
Key Point: 2 * (length + width) is equivalent to 2 * length + 2 * width — both count each of the rectangle's four sides exactly once, just grouped differently.
Key Concepts
doublearithmetic expression
Approach 2: Java 8
Java
import java.util.function.DoubleBinaryOperator;
public class CalculatePerimeterOfRectangleLambda {
public static void main(String[] args) {
double length = 10.0;
double width = 5.0;
// The perimeter formula is stored as a lambda, named for what it computes
DoubleBinaryOperator perimeterOf = (l, w) -> 2 * (l + w);
double perimeter = perimeterOf.applyAsDouble(length, width);
System.out.println("Perimeter: " + perimeter);
}
}
Output
Perimeter: 30.0
Core Logic
The perimeter formula can be wrapped in a named lambda, turning 'compute a perimeter' into a small reusable function.
How It Works
- 1
DoubleBinaryOperator perimeterOf = (l, w) -> 2 * (l + w);stores the formula as a lambda. - 2
perimeterOf.applyAsDouble(length, width)calls it, returning the same result the inline expression would. - 3The result is printed exactly as before.
With
length = 10.0 and width = 5.0, perimeterOf.applyAsDouble(10.0, 5.0) returns 30.0.💡
Key Point: Storing the formula as perimeterOf keeps the geometric meaning attached to the lambda's name, rather than buried inside an inline expression at each call site.
Key Concepts
DoubleBinaryOperatorfunctional interfacelambda expression