Java Program to find area of circle
In this program let us create a Java program to find area of circle.
Program
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class AreaofCircle {
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 area = Math.PI * radius * radius;
System.out.println("Area of a circle is " + area);
}
}
Let us understand the program by breaking into simple parts:
public class AreaofCircle
: Any Java program starts with a class, in this case the class name is AreaofCirclepublic static void main(String[] args)
: main is the entry point for any Java program.int radius = 0;
: variable radius is declared and initializedBufferedReader 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.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 inBufferedReader br = new BufferedReader(new InputStreamReader(System.in))
.br.readLine()
: The readLine() method of BufferedReader class in Java is used to read one line text at a time.Exception Handling
: Try catch block is used for exception handling. NumberFormatException and IoException are sub class of Exception class.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.double area = Math.PI * radius * radius;
: Math.PI is a static final double constant in Java which is provided by java.lang.Math class. This line calculates the area of circle given the radius.
Output
Please enter radius of a circle
8
Area of a circle is 201.06192982974676