Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to count , how many times a method is called using different object.

Java Code Example — OOP Programs

ADVERTISEMENT

Java Program to count , how many times a method is called using different object.

Objective

Write a Java program to count how many times a method is called across multiple object instances.

Algorithm / Approach

  1. Create a class Counter.
  2. Declare a static integer variable count = 0.
  3. Define a method counter() that increments count.
  4. Define a method display() that prints the value of count.
  5. In main, create a Counter object and call counter() twice.
  6. Create a second Counter object and call counter() twice again.
  7. Call display() to print the final count.
Counter.java
class Counter {
 static int count = 0;
 void counter(){
  count++;
 }
 void display() {
  System.out.println("Total time- "+count);
 }
 public static void main(String[] a)
 {
  Counter c = new Counter();
  c.counter();
  c.counter();
  Counter c2 = new Counter();
  c2.counter();
  c2.counter();
  c2.display();
 }
}

Expected Output

Total time-4

Explanation of the Program

  • This is a practical application of the static keyword. Since we want to track the total number of method calls across the entire program regardless of which object made the call, we must use a static variable.
  • If count were not static, the first object would count to 2, and the second object would separately count to 2. By making it static, the count continues seamlessly from 2 up to 4.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT