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?
public class Demo {
    static int x = 5;
    static void change() {
        x = 10;
    }
    public static void main(String[] args) {
        System.out.println(x);
        change();
        System.out.println(x);
    }
}
A5\n5
B5\n10
C10\n5
D10\n10
Step-by-Step Solution
Solution:
  1. Step 1: Understand static variable and method behavior

    Variable x is static and initially 5. The static method change() sets x to 10.
  2. Step 2: Trace the program output

    First print outputs 5. After calling change(), x becomes 10. Second print outputs 10.
  3. Final Answer:

    5\n10 -> Option B
  4. Quick Check:

    Static variable update reflected = 5 then 10 [OK]
Quick Trick: Static variables keep changes across static methods [OK]
Common Mistakes:
  • Assuming x does not change after method call
  • Confusing instance and static variables
  • Expecting output order reversed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes