Calculate Circumference of Circle in Java
Problem
A circle's circumference is the distance around it, and it scales directly with the radius rather than the radius squared like area does.
Given the radius of a circle, calculate its circumference.
Java Program
public class CalculateCircumferenceOfCircle {
public static void main(String[] args) {
double radius = 7.0;
double circumference = 2 * Math.PI * radius; // 2 * π * r
System.out.println("Circumference: " + String.format("%.2f", circumference));
}
}Output
Core Logic
Multiplying 2, Math.PI, and the radius together gives the circumference directly, formatted to two decimal places for a clean result.
- 1
radiusholds7.0. - 2
2 * Math.PI * radiusevaluates to approximately43.982. - 3
String.format("%.2f", circumference)rounds that to two decimal places,43.98. - 4The formatted string is printed with a label.
radius = 7.0, 2 * Math.PI * 7.0 gives approximately 43.982, which rounds to 43.98.Key Point: Circumference grows linearly with radius (double the radius, double the circumference), while area grows with the square of the radius — the same Math.PI constant drives both, but the formulas scale very differently.
Key Concepts
Approach 2: Java 8
import java.util.function.DoubleUnaryOperator;
public class CalculateCircumferenceOfCircleLambda {
public static void main(String[] args) {
double radius = 7.0;
// The circumference formula is stored as a reusable lambda
DoubleUnaryOperator circumferenceOf = r -> 2 * Math.PI * r;
double circumference = circumferenceOf.applyAsDouble(radius);
System.out.println("Circumference: " + String.format("%.2f", circumference));
}
}
Output
Core Logic
The circumference formula can be stored as a reusable lambda instead of being written inline.
- 1
DoubleUnaryOperator circumferenceOf = r -> 2 * Math.PI * r;stores the formula as a lambda. - 2
circumferenceOf.applyAsDouble(radius)calls it, returning the same value the inline expression would. - 3The result is formatted and printed exactly as before.
radius = 7.0, circumferenceOf.applyAsDouble(7.0) returns approximately 43.982, which rounds to 43.98.Key Point: Having both areaOf (see the Area of Circle page) and circumferenceOf as separate lambdas makes it easy to compute either measurement for the same radius without duplicating logic.