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
}
}