Circumference and circular area

The user is first prompted to enter a radius. Then the circumference and area of the circle are calculated, rounded and output to the screen.

Code Example

import java.util.Scanner;

class CircumferenceCircularArea {
	public static void main(String[] args) {
		Scanner reader = new Scanner(System.in);
		double r, area, circumference;
	
		System.out.print("Please enter radius: ");
		r = reader.nextDouble();
		reader.close();
	
		// calculation of circumference
		circumference = 2 * Math.PI * r;
	
		// calculation of circular area
		// Math.pow(base, exponent): Returns base raised to the power exponent
		area = Math.PI * Math.pow(r, 2);
	
		System.out.println("Circumference: " + String.format("%1.2f", circumference));
		System.out.println( "Circular Area: " + String.format("%1.2f", area));
	}
}
Output
Please enter radius: 4.5
Circumference: 28.27
Circular Area: 63.62

Code Explanation

import java.util.Scanner; imports the Scanner class from the java.util package. This class is used to read user input from the console.

class CircumferenceCircularArea declares a class named CircumferenceCircularArea.

public static void main(String[] args) is the main method of the program where the execution starts. It takes an array of strings as a parameter (although it is not used in this program).

The following lines declare variables:

Scanner reader = new Scanner(System.in);
double r, area, circumference;

Here, reader is an instance of the Scanner class that is used to read user input. r is a double variable to store the radius entered by the user, and area and circumference are double variables to store the calculated values.

System.out.print("Please enter radius: "); displays a prompt message asking the user to enter the radius.

r = reader.nextDouble(); reads a double value entered by the user using the nextDouble() method of the Scanner class. The value entered by the user is stored in the r variable.

reader.close(); closes the Scanner object to release system resources after reading the user input.

circumference = 2 * Math.PI * r; calculates the circumference of the circle using the formula 2 * π * r, where Math.PI represents the mathematical constant π.

area = Math.PI * Math.pow(r, 2); calculates the circular area using the formula π * r^2. The Math.pow(base, exponent) function is used to raise r to the power of 2.

The following lines print the calculated values:

System.out.println("Circumference: " + String.format("%1.2f", circumference));
System.out.println("Circular Area: " + String.format("%1.2f", area));

The System.out.println() statements display the calculated circumference and circular area values. The String.format("%1.2f", value) is used to format the double values with two decimal places before displaying them.