Calculate Area of Circle in Java
beginner· Basics & I/O · Geometry
Problem
A circle's area scales with the square of its radius, using the mathematical constant π that Java provides directly as Math.PI.
Given the radius of a circle, calculate its area.
Input
radius = 7.0
Output
Area: 153.94
Java Program
Java
public class CalculateAreaOfCircle {
public static void main(String[] args) {
double radius = 7.0;
double area = Math.PI * radius * radius; // π * r²
System.out.println("Area: " + String.format("%.2f", area));
}
}Output
Area: 153.94
Core Logic
Multiplying Math.PI by the radius squared gives the area directly, formatted to two decimal places for a clean result.
How It Works
- 1
radiusholds7.0. - 2
Math.PI * radius * radiusevaluates to approximately153.938. - 3
String.format("%.2f", area)rounds that to two decimal places,153.94, since π is irrational and the raw result has many more digits. - 4The formatted string is printed with a label.
For
radius = 7.0, Math.PI * 7.0 * 7.0 gives approximately 153.938, which rounds to 153.94.💡
Key Point: Math.PI is a built-in constant, not something to hardcode as 3.14 — it carries far more precision, which matters once the result is rounded rather than truncated.
Key Concepts
doubleMath.PIString.format()
Approach 2: Java 8
Java
import java.util.function.DoubleUnaryOperator;
public class CalculateAreaOfCircleLambda {
public static void main(String[] args) {
double radius = 7.0;
// The area formula is stored as a reusable lambda
DoubleUnaryOperator areaOf = r -> Math.PI * r * r;
double area = areaOf.applyAsDouble(radius);
System.out.println("Area: " + String.format("%.2f", area));
}
}
Output
Area: 153.94
Core Logic
The area formula can be stored as a reusable lambda instead of being written inline.
How It Works
- 1
DoubleUnaryOperator areaOf = r -> Math.PI * r * r;stores the formula as a lambda. - 2
areaOf.applyAsDouble(radius)calls it, returning the same value the inline expression would. - 3The result is formatted and printed exactly as before.
With
radius = 7.0, areaOf.applyAsDouble(7.0) returns approximately 153.938, which rounds to 153.94.💡
Key Point: Once areaOf exists as a lambda, it can be reused for any number of radius values without repeating the formula each time.
Key Concepts
DoubleUnaryOperatorfunctional interfacelambda expression