## 1.概述。

In this quick tutorial, we’ll illustrate how to calculate the area of a circle in Java.

We’ll be using the well-known math formula: r^2 * PI.

## 2.圆面积计算方法

Let’s first create a method that will perform the calculation:

``````private void calculateArea(double radius) {
System.out.println("The area of the circle [radius = " + radius + "]: " + area);
}``````

### 2.1.将半径作为一个命令行参数来传递

Now we can read the command line argument and calculate the area:

``````double radius = Double.parseDouble(args);

When we compile and run the program:

``````java CircleArea.java
javac CircleArea 7``````

we’ll get the following output:

``The area of the circle [radius = 7.0]: 153.93804002589985``

### 2.2.从键盘上读取半径

Another way to get the radius value is to use input data from the user:

``````Scanner sc = new Scanner(System.in);

The output is the same as in the previous example.

## 3.一个圆圈班

Besides calling a method to calculate the area as we saw in section 2, we can also create a class representing a circle:

``````public class Circle {

}

// standard getter and setter

private double calculateArea() {
}

public String toString() {
return "The area of the circle [radius = " + radius + "]: " + calculateArea();
}
}``````

We should note a few things. First of all, we don’t save the area as a variable, since it is directly dependent on the radius, so we can calculate it easily. Secondly, the method that calculates the area is private since we use it in the toString() method. The toString() method shouldn’t call any of the public methods in the class since those methods could be overridden and their behavior would be different than the expected.

We can now instantiate our Circle object:

``Circle circle = new Circle(7);``

The output will be the, of course, the same as before.

## 4.总结

In this short and to-the-point article, we showed different ways of calculating the area of a circle using Java.

As always, complete source code can be found over on GitHub.  