Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Java - Static Keyword
What will be the output of this code?
class Test {
    static int count = 0;
    Test() {
        count++;
    }
    static int getCount() {
        return count;
    }
    public static void main(String[] args) {
        new Test();
        new Test();
        System.out.println(Test.getCount());
    }
}
A0
B2
C1
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand static variable and constructor

    Static variable count increments each time a Test object is created.
  2. Step 2: Trace object creation and method call

    Two Test objects are created, so count becomes 2. getCount() returns 2.
  3. Final Answer:

    2 -> Option B
  4. Quick Check:

    Static count increments with each new object = 2 [OK]
Quick Trick: Static variables shared across all instances [OK]
Common Mistakes:
  • Thinking static variables reset per object
  • Expecting count to be 0 or 1
  • Confusing static method usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes