Variable Shadowing with an Instance Variable
Consider the following ShadowError class. When the main method is executed, the program prints 0. Which of the following statements best explains this behavior?
public class ShadowError {
int counter = 0;
public void increase() {
for (int i = 0; i < 5; i++) {
int counter = 0;
counter += i;
}
System.out.println(counter);
}
public static void main(String[] args) {
ShadowError s = new ShadowError();
s.increase();
}
}
A
The variable ‘counter’ is redeclared inside the loop, which shadows the instance variable and prevents its intended update.
B
The counter should be incremented outside of the loop to accumulate the total.
C
The inner loop variable ‘i’ is not used in any meaningful computation.
D
The loop termination condition is off, leading to fewer iterations than expected.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | samyrabahfc | 2 | 2 | 0m 00s | 200 |
| #2 | zgj07310417 | 0 | 1 | 0m 23s | -33 |
| #3 | lsj08030922 | 1 | 1 | 4m 25s | -165 |
Items per page:
10
1 – 3 of 3
