Does Java support static local variables inside method?

To answer this question, first we must know the concept of static with variables. Static variables are clearly and more elaborately discussed in . For our question sake, I quote a few points about static variables.

  1. A static variable does not maintain encapsulation.
  2. There will be only one location for static variable accessed by all the objects of the whole class. For this reason, static variables are known as "class variables"; in the sense, the static variable is only one for all the objects of the class.
  3. Only instance variable is declared static so that its scope is for all the methods and for all the objects.

Now let us go into the answer. By rule, when the static variable scope (or visible) is for the whole class, by common sense, how a local variable be declared static. A local variable scope is within the method where it is declared. If the local variable is declared static, the meaning of static is lost. If the local variable is static, the purpose of static variable is bypassed. For this reason, compiler does not allow static local variables.

Finally, Local variables cannot be static in Java. Only instance variables can be static.

Following code raises compilation error.

public void display()
  static int marks = 80;		     // raises compilation error

Next teasing question:

Do the local variables declared in a static method are implicitly static or can we assume static?

If you think implicitly static, it is a compilation error as discussed in the previous question that local variables cannot be static. The local variables in a static method are simply just local variables (non-static) only equivalent to declared in a non-static method. That is, the variables declared in a static method do not have any special meaning anyhow.

Similarly, passing a static variable to a method parameter does not have any special effect. It is simply as if passed a non-static variable.

If a Programmer needs static variables, he must declare them as instance variables only outside any method.

Have tried static classes in Java? Your answer will be mostly wrong.

Leave a Comment

Your email address will not be published.