class
You cannot have static variables declared inside a method
In this example we shall show you the reason why you cannot have static variables declared inside a method. The steps of the example are described below:
- We have a class,
StaticVar
that consists of aprocess()
method, where it sets astatic
int variable and prints it. - We make a new instance of the
StaticVar
in amain()
method and call itsprocess()
method. - A
java.lang.Error
occurs, and the unresolved compilation problem is that the static modifier is not permitted,
as described in the code snippet below.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 | package futuretest; public class StaticVar { public static void main(String[] argv) { StaticVar t = new StaticVar(); t.process(); } void process() { static int a = 42 ; // EXPECT COMPILE ERROR System.out.println( "Process: " + a); } } |
This was an example of explaining why you cannot have static variables declared inside a method in Java.