Saturday, July 19, 2008

Can a local variable be static..? uhh..why not?

No! - that's a very straight forward answer to that question and most simple one. In java the local variables can not be static - burn this in your mind. But Why??. The local variables are those which are declared inside a method body, so they have scope only for the method execution period. Any static thing in java belongs to the class and not to the instance. Whenever the method is called the method variables are in the memory area of the thread executing that method, so they are on stack. On the other hand the objects and static members of a class are on heap. Static things are to live throughout the method calls and when they are inside the method body (on stack) they can't live outside the scope of method, hence its ridiculous and illogical to have static variables inside a method body.
For the exam, you need not know why, just remember that a local variable can never be static - compiler will complain.

No comments: