Java ProgramsBasics & I/OCalculate Area of Rectangle

Calculate Area of Rectangle in Java

beginner·  Basics & I/O  ·  Geometry

Problem

A rectangle's area is simply its length multiplied by its width — no special constants or functions needed.

Given the length and width of a rectangle, calculate its area.

Input
length = 10.0, width = 5.0
Output
Area: 50.0

Java Program

Java
public class CalculateAreaOfRectangle { public static void main(String[] args) { double length = 10.0; double width = 5.0; double area = length * width; // length times width System.out.println("Area: " + area); } }

Output

Area: 50.0

Core Logic

Multiplying length by width gives the area directly, in a single expression.

How It Works
  1. 1length holds 10.0 and width holds 5.0.
  2. 2length * width evaluates to 50.0.
  3. 3The result is stored in area and printed with a label.
For length = 10.0 and width = 5.0, 10.0 * 5.0 gives 50.0.
💡

Key Point: A rectangle where length equals width is a square — the same formula works either way, since a square is just a special case of a rectangle.

Key Concepts

doublemultiplication

Approach 2: Java 8

Java
import java.util.function.DoubleBinaryOperator; public class CalculateAreaOfRectangleLambda { public static void main(String[] args) { double length = 10.0; double width = 5.0; // The multiplication logic is stored as a lambda, named for what it computes DoubleBinaryOperator areaOf = (l, w) -> l * w; double area = areaOf.applyAsDouble(length, width); System.out.println("Area: " + area); } }

Output

Area: 50.0

Core Logic

The multiplication can be wrapped in a named lambda, turning 'compute an area' into a small reusable function.

How It Works
  1. 1DoubleBinaryOperator areaOf = (l, w) -> l * w; stores the multiplication logic as a lambda.
  2. 2areaOf.applyAsDouble(length, width) calls it, returning the same result the inline multiplication would.
  3. 3The result is printed exactly as before.
With length = 10.0 and width = 5.0, areaOf.applyAsDouble(10.0, 5.0) returns 50.0.
💡

Key Point: Naming the lambda areaOf instead of a generic multiply makes the intent clear at the call site, even though the underlying operation is just multiplication.

Key Concepts

DoubleBinaryOperatorfunctional interfacelambda expression

Related Programs