Bird
0
0

Consider this class:

hard📝 Application Q9 of 15
Java - Classes and Objects
Consider this class:
class Counter {
  int count = 0;
  public void increment() {
    int count = 5;
    count++;
  }
  public int getCount() {
    return count;
  }
}
What will getCount() return after calling increment() once?
A1
B0
C5
D6
Step-by-Step Solution
Solution:
  1. Step 1: Understand variable shadowing in increment()

    Inside increment(), a local variable 'count' is declared and set to 5, then incremented to 6. This does not affect the instance variable.
  2. Step 2: Check what getCount() returns

    getCount() returns the instance variable 'count', which remains 0 because increment() did not change it.
  3. Final Answer:

    0 -> Option B
  4. Quick Check:

    Local variable shadows instance variable, instance unchanged [OK]
Quick Trick: Local variables hide instance variables inside methods. [OK]
Common Mistakes:
  • Assuming instance variable changes when local variable changes.
  • Confusing local and instance variable scopes.
  • Expecting incremented value to affect instance variable.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes