Java ProgramsBasics & I/OCalculate Circumference of Circle

Calculate Circumference of Circle in Java

beginner·  Basics & I/O  ·  Geometry

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.

Input
radius = 7.0
Output
Circumference: 43.98

Java Program

Java
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

Circumference: 43.98

Core Logic

Multiplying 2, Math.PI, and the radius together gives the circumference directly, formatted to two decimal places for a clean result.

How It Works
  1. 1radius holds 7.0.
  2. 22 * Math.PI * radius evaluates to approximately 43.982.
  3. 3String.format("%.2f", circumference) rounds that to two decimal places, 43.98.
  4. 4The formatted string is printed with a label.
For 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

doubleMath.PIString.format()

Approach 2: Java 8

Java
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

Circumference: 43.98

Core Logic

The circumference formula can be stored as a reusable lambda instead of being written inline.

How It Works
  1. 1DoubleUnaryOperator circumferenceOf = r -> 2 * Math.PI * r; stores the formula as a lambda.
  2. 2circumferenceOf.applyAsDouble(radius) calls it, returning the same value the inline expression would.
  3. 3The result is formatted and printed exactly as before.
With 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.

Key Concepts

DoubleUnaryOperatorfunctional interfacelambda expression

Related Programs