Bird
0
0

What will be the output of the following Java program?

medium📝 Predict Output Q5 of 15
Java - Static Keyword
What will be the output of the following Java program?
class Counter {
    static int total = 0;
    Counter() {
        total += 2;
    }
    public static void main(String[] args) {
        new Counter();
        new Counter();
        new Counter();
        System.out.println(total);
    }
}
A6
B3
C0
D2
Step-by-Step Solution
Solution:
  1. Step 1: Understand static variable behavior

    The static variable 'total' is shared among all instances of the class.
  2. Step 2: Analyze constructor increments

    Each time a new Counter object is created, 'total' increases by 2.
  3. Step 3: Calculate total after three objects

    3 objects * 2 increments each = 6.
  4. Final Answer:

    6 -> Option A
  5. Quick Check:

    Static variables accumulate changes across instances [OK]
Quick Trick: Static variables keep shared state across all objects [OK]
Common Mistakes:
  • Assuming 'total' resets for each object
  • Confusing instance and static variables
  • Ignoring increments in constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes