11. Why can’t we initialize a static variable inside a method?

Love and Share

Answer:  We cannot declare a static variable within main methodin Java because Static variables have to be declared at a class level. A static variable means that this variable belongs to the entire class and not any particular instance. So In java, only class variables can be declared as static.

Any variable declared within a method is supposed to be local to the method (It gets stored in the method stack in the JVM, which is one per thread), and static variables are common to all objects of a class (obviously a class can be invoked by many threads . So, Static variables are class variables, and don’t make sense to be limited in scope to a method.

Love and Share

Leave a Reply

Your email address will not be published. Required fields are marked *