Java Program to Calculate Area of a Circle
The Mathematical formula to find Area of a Circle is : A= πr2 or we can write it as given below.
area = pi * radius * radius
Here is the simple source code to find the area of the circle. Compiled successfully on windows operating system.
Output:
area = pi * radius * radius
So, to find Area of a circle we need the values of 'pi' and radius. In java we have predefined Mathematical value for pi is defined in java.lang.Math.PI = 3.141592653589793. PI is a static final value.
In our program we need to read radius value from the console by using BufferedReader or Console classes.
package com.javabynataraj; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; //http://javabynataraj.blogspot.com public class AreaOfCircle { public static void main(String[] args) { int radius = 0; double area; System.out.print("Please enter radius of a circle: "); try { BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); radius = Integer.parseInt(br.readLine()); } // if any invalid value entered 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); } area = Math.PI * radius * radius; System.out.println("Area of a circle is: " + area); } }After the compilation enter the radius value and press enter.
Output:
Reference Books: