Java Program to find perimeter of circle

In this program let us create a Java program to print the perimeter of circle.

Program

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
public class PerimeterofCircle {
    public static void main(String[] args) {
        int radius = 0;
        System.out.println("Please enter radius of a circle");
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            radius = Integer.parseInt(br.readLine());
        } catch (NumberFormatException ne) {
            System.out.println("Invalid radius value" + ne);
            System.exit(0);
        } catch (IOException ioe) {
            System.out.println("IO Error :" + ioe);
            System.exit(0);
        }
        double perimeter = 2 * Math.PI * radius;
        System.out.println("Perimeter of a circle is " + perimeter);
    }
}

Let us understand the program by breaking into simple parts:

  1. public class PerimeterofCircle: Any Java program starts with a class, in this case the class name is PerimeterofCircle
  2. public static void main(String[] args): main is the entry point for any Java program.
  3. int radius = 0; : variable radius is declared and initialized
  4. BufferedReader and InputStream: BufferedReader is a class which simplifies reading text from a character input stream. The BufferedReader object br is initialized by calling one of its constructors that takes Reader object as a method argument and considered one of its subclass the InputStreamReader to read InputStream. br object variable will creates a variable space with default value. The constructor of this class accepts an InputStream object as a parameter.
  5. System.in : System.in corresponds to keyboard input or another input source specified by the host environment or user. By wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line as shown in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)).
  6. br.readLine() : The readLine() method of BufferedReader class in Java is used to read one line text at a time.
  7. Exception Handling : Try catch block is used for exception handling. NumberFormatException and IoException are sub class of Exception class.
  8. System.exit(0) : The function System. exit(0) is used when we want to terminate the execution of the program at any instance. As soon as System. exit(0) function is invoked, it terminates the execution, ignoring the rest of the statements of the program.
  9. double perimeter = 2 * Math.PI * radius; : Math.PI is a static final double constant in Java which is provided by java.lang.Math class. This line calculates the perimeter of circle given the radius.

Output

Please enter radius of a circle
12
Perimeter of a circle is 75.39822368615503