Skip to main content

Practical-1

Write a Java Program find the area of circle.


Introduction

Welcome to the programming world! This tutorial is a step by step guide to write a simple Java program which will find the area of a circle.

Code

CalculateArea.java
//importing the utility class Scanner to take user input
import java.util.Scanner;

//Creating the class name
public class CalculateArea {

//Define the main function/method
public static void main(String[] args) {

//Declare a double type radius to store the radius of the circle
double radius;

//creating a new Scanner object
Scanner sc = new Scanner(System.in);

//Printing the prompt to the user and storing the input in radius
System.out.println("Please enter the radius of the circle: ");
radius = sc.nextDouble();

//Calculating the area of circle
double area = 3.14 * radius * radius;

//Printing the output to the user
System.out.println("The area of the circle is: "+area);
}
}

Output

Please enter the radius of the circle: 10 The area of the circle is: 314.0

Explanation

The above code calculates the area of a circle. First we import a utility class called Scanner to take user input. Then we create a class name and declare the main function in it. After that we declare a double type variable to store the radius of the circle taken from the user. Then we create a new Scanner object and prompt the user to enter the radius. The input from the user is stored in radius. We then calculate the area of circle using area = 3.14 * radius * radius. In the end we print the output to the user.

To run the code, you need to have any java compiler installed in your system, like Eclipse IDE. After writing the code in the editor, compile and run it. Your output should be displayed.