Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Java - Static Keyword
What will be the output of this code?
class Demo {
  static int x = 5;
  void change() {
    x = 10;
  }
}
public class Test {
  public static void main(String[] args) {
    Demo d1 = new Demo();
    Demo d2 = new Demo();
    d1.change();
    System.out.println(d2.x);
  }
}
A5
B10
C0
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand static variable sharing

    Variable x is static, so d1 and d2 share the same x.
  2. Step 2: Trace method call and print

    d1.change() sets x to 10. Printing d2.x prints the updated value 10.
  3. Final Answer:

    10 -> Option B
  4. Quick Check:

    Static variable updated by one object = A [OK]
Quick Trick: Static variables updated by one object affect all instances [OK]
Common Mistakes:
  • Assuming d2.x remains 5 after d1 changes it
  • Thinking static variables are instance-specific
  • 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