Write a program to calculate the area of circle and cylinder by creating methods named areaOfCircle and areaOfCylinder in a class named Area and using a constant variable PI=3.14.
Objective
Calculate the area of a circle and cylinder using methods and a class-level constant variable.
Algorithm / Approach
- Create an
Areaclass with a constantfinal double PI = 3.14;. - Define
areaOfCircle(int r)which calculates and printsPI * r * r. - Define
areaOfCylinder(int r, int h)which calculates and prints2 * PI * r * h(Note: this formula calculates the lateral surface area, not total volume). - In the
mainmethod, take the required radii and height as input from the user. - Instantiate the
Areaclass and call both methods.
Area.java
import java.util.Scanner;
class Area {
final double PI = 3.14;
void areaOfCircle(int r) {
double ar = PI*r*r;
System.out.println("Circle Area= "+ar);
}
void areaOfCylinder(int r, int h) {
double ar = 2*PI*r*h;
System.out.print("Cylinder Area= "+ar);
}
public static void main(String[] a)
{
Area ar = new Area();
Scanner s=new Scanner(System.in);
System.out.print("Enter Circle Radius: ");
int r = s.nextInt();
System.out.print("Enter Cylinder Radius: ");
int r2 = s.nextInt();
System.out.print("Enter Cylinder Height: ");
int h = s.nextInt();
ar.areaOfCircle(r);
ar.areaOfCylinder(r2,h);
}
}
Expected Output
Enter Circle Radius: 7 Enter Cylinder Radius: 7 Enter Cylinder Height: 10 Circle Area= 153.86 Cylinder Area= 439.6
Explanation of the Program
- The
finalkeyword in Java is used to declare constants. Once afinalvariable is initialized, its value cannot be changed. - Declaring
PIat the class level allows multiple methods (areaOfCircleandareaOfCylinder) to share the same constant value without redefining it. - This demonstrates code reusability and maintainability.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Trying to modify a
finalvariable inside a method, which will trigger a compilation error.