Java interfaces and constants: what happens when code attempts to modify an interface field inside a loop? interface Count { short counter = 0; // implicitly public static final void countUp(); } public class TestCount implements Count { public static void main(String[] args) { TestCount t = new TestCount(); t.countUp(); } public void countUp() { for (int x = 6; x > counter; x--, ++counter) { System.out.print(" " + counter); } } }
-
A0 1 2
-
B1 2 3
-
C0 1 2 3
-
D1 2 3 4
-
ECompilation fails
Answer
Correct Answer: Compilation fails
Explanation
Introduction / Context: In Java, every field declared in an interface is implicitly public, static, and final. Attempting to change such a field at runtime violates the final constraint and should be caught at compile time. This question verifies familiarity with these interface rules and constant behavior.
Given Data / Assumptions:
- Interface Count declares short counter = 0.
- Class TestCount implements Count and references counter directly.
- The for loop tries to execute ++counter in its update expression.
Concept / Approach: Because Count.counter is a compile-time constant (final), it cannot be incremented. The statement ++counter attempts to assign a new value to a final variable, which is illegal. The compiler flags the increment as an error.
Step-by-Step Solution:
Recognize that interface fields are final → immutable.Loop header contains ++counter → tries to modify a final field.Compiler emits an error similar to "cannot assign a value to final variable counter".No bytecode is generated; program does not run.Verification / Alternative check: A correct approach would use a local variable, e.g., short c = counter; then modify c within the loop while comparing against a fixed boundary.
Why Other Options Are Wrong:
- All printed sequences assume successful compilation and execution.
Common Pitfalls: Forgetting the implicit modifiers on interface fields; assuming counter is an instance field that can be changed.
Final Answer: Compilation fails