Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q13 of 15
Java - Static Keyword
What will be the output of the following code?
public class Test {
    static int count = 0;
    static void increment() {
        count++;
    }
    public static void main(String[] args) {
        increment();
        increment();
        System.out.println(count);
    }
}
A2
B1
CCompilation error
D0
Step-by-Step Solution
Solution:
  1. Step 1: Understand static variable and method behavior

    The static variable count starts at 0 and is shared by all calls.
  2. Step 2: Trace method calls

    Each call to increment() increases count by 1. Called twice, count becomes 2.
  3. Final Answer:

    2 -> Option A
  4. Quick Check:

    Two increments = count 2 [OK]
Quick Trick: Static variables keep value across static method calls [OK]
Common Mistakes:
  • Thinking count resets each call
  • Confusing static and instance variables
  • Expecting compilation error due to static usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes