Java method-local static variables are not allowed: what happens when a method declares "static int i" locally?\n\npublic class Test {\n public int aMethod() {\n static int i = 0; // illegal: static not allowed in local context\n i++;\n return i;\n }\n public static void main(String args[]) {\n Test test = new Test();\n test.aMethod();\n int j = test.aMethod();\n System.out.println(j);\n }\n}

Difficulty: Easy

Correct Answer: Compilation fails.

Explanation:


Introduction / Context:
Unlike C/C++, Java does not permit local variables to be declared static inside a method body. Only class members (static fields, static methods, static initializers, and static nested classes) may be static. This question checks awareness of that restriction.



Given Data / Assumptions:

  • aMethod attempts to declare static int i inside the method.
  • The rest of the code uses i to accumulate calls and prints the result.


Concept / Approach:
The compiler rejects the declaration static int i within the method scope with an error like "Illegal static declaration in inner class" or "modifier static not allowed here." Therefore, the program never compiles, and none of the logic after it executes.



Step-by-Step Solution:

Parse aMethod and encounter static int i in a local context.Java language rules prohibit static local variables.Compilation fails; main cannot run.


Verification / Alternative check:
To achieve similar behavior, make i a static field of the class (static int i;) or an instance field if per-object state is desired.



Why Other Options Are Wrong:

  • 0 / 1 / 2: All assume successful compilation and execution.
  • Runtime exception: The program does not reach runtime.


Common Pitfalls:
Porting patterns from C where static locals are allowed; misunderstanding scope and lifetime rules in Java.



Final Answer:
Compilation fails.

More Questions from Declarations and Access Control

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion