0

When I was experimenting on recursion in Java, I encountered an error which didn't allow me to declare a static variable inside a non-static method.

public class TestClass{
    
    public void recurse(){
        static int a = 1; //why is this wrong? 
        if(a == 11){
            return;
        }
        a++;
        
        recurse();
    }
}

If I were to do this in a C++ program, there would not have been any issue. Why is it that we cannot do this in Java? I know if I declared the variable outside the method there would not have been any problem. But my question is why is it that it cannot be declared inside?

Also, for some reason if we cannot declare a static variable inside a non-static method, why is it that we can declare a instance variable inside a static method?

public class Main {

    public static void main(String[] args) {
        int a = 9; //non-static variable declared inside a static method
    }

}
  • 2
    You can't declare a `static` thing in any method. And `int a ` in your last snippet is neither static nor non-static. – ernest_k Feb 25 '21 at 10:50
  • 2
    `int a` in your last example is not an instance variable, but a local variable. – OH GOD SPIDERS Feb 25 '21 at 10:52
  • 1
    If your question about local static variables *was not asked by accident*, then read through this: [Why there is no local static variable in Java?](https://stackoverflow.com/questions/12274375/why-there-is-no-local-static-variable-in-java) – ernest_k Feb 25 '21 at 10:54
  • *... is not an instance variable, but a local variable."* - And it would be a local variable in C++ as well! – Stephen C Feb 25 '21 at 11:34

0 Answers0