Java Program to Calculate Area of Circle
area = Math.PI * radius * radius where radius is the circle's radius; for example, double area = Math.PI * radius * radius;.Examples
How to Think About It
Algorithm
Code
import java.util.Scanner; public class CircleArea { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter radius of circle: "); double radius = scanner.nextDouble(); double area = Math.PI * radius * radius; System.out.println("Area of circle: " + area); scanner.close(); } }
Dry Run
Let's trace the program with radius = 5 through the code
Input radius
User enters 5, so radius = 5.0
Calculate area
area = Math.PI * 5.0 * 5.0 = 3.141592653589793 * 25 = 78.53981633974483
Print result
Output "Area of circle: 78.53981633974483"
| Step | Radius | Area |
|---|---|---|
| Input | 5.0 | - |
| Calculate | 5.0 | 78.53981633974483 |
| Output | 5.0 | 78.53981633974483 |
Why This Works
Step 1: Getting radius input
We use Scanner to read the radius value from the user so the program can work with any circle size.
Step 2: Calculating area
The formula area = Math.PI * radius * radius calculates the space inside the circle using the radius squared and pi.
Step 3: Displaying the result
We print the area so the user can see the answer clearly.
Alternative Approaches
import java.util.Scanner; public class CircleArea { public static double calculateArea(double r) { return Math.PI * r * r; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter radius: "); double radius = scanner.nextDouble(); double area = calculateArea(radius); System.out.println("Area of circle: " + area); scanner.close(); } }
import java.util.Scanner; public class CircleArea { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter radius: "); float radius = scanner.nextFloat(); float area = (float)(Math.PI * radius * radius); System.out.println("Area of circle: " + area); scanner.close(); } }
Complexity: O(1) time, O(1) space
Time Complexity
The calculation uses a fixed number of operations regardless of input size, so it is constant time O(1).
Space Complexity
Only a few variables are used to store radius and area, so space is constant O(1).
Which Approach is Fastest?
All approaches run in constant time; using a method adds clarity but no significant speed difference.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct calculation in main | O(1) | O(1) | Simple quick calculation |
| Separate method for calculation | O(1) | O(1) | Code reuse and clarity |
| Using float instead of double | O(1) | O(1) | Memory saving with less precision |
double for precise calculations involving decimals like area.