Skip to main content

ProwessApps

Learn · Practice · Excel

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.

Java Code Example — OOP Programs

ADVERTISEMENT

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

  1. Create an Area class with a constant final double PI = 3.14;.
  2. Define areaOfCircle(int r) which calculates and prints PI * r * r.
  3. Define areaOfCylinder(int r, int h) which calculates and prints 2 * PI * r * h (Note: this formula calculates the lateral surface area, not total volume).
  4. In the main method, take the required radii and height as input from the user.
  5. Instantiate the Area class 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 final keyword in Java is used to declare constants. Once a final variable is initialized, its value cannot be changed.
  • Declaring PI at the class level allows multiple methods (areaOfCircle and areaOfCylinder) 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 final variable inside a method, which will trigger a compilation error.
ADVERTISEMENT