On various specialized Internet resources there are many opinions on this issue. Sometimes these opinions are diametrically different from each other. For example, there is a whole layer of practitioners who do not strongly recommend doing so (mainly from the community of programmers who work with the C / C ++ language). Others advocate that variables be declared as “locally” as possible. What practice, in your opinion, is more justified?
Moving on ... I would like to understand what happens to the stack when we declare a variable in a loop. Do I understand correctly that after each iteration passed, those local variables that were declared directly in the body of the loop itself go through the removal process from the stack (pop operation is performed), and then they are loaded again (this happens during the new iteration, In this case, the push operation is triggered? I'm not sure that this is the case, but the following test code brought me to such reflections:
class Test { public static void main(String[] args) { for(int i = 0; i < 5; i++) { if(i == 1) System.out.println(j); int j = 0; } } } /* Compilation Errors Detected Line: 6 cannot find symbol symbol: variable j location: class Test */ As we can see, the compiler indicates to us that within the scope in which we are trying to access our local variable, there is actually no variable with such an identifier (although we already declared it in the previous iteration). What else confuses me is that if you look at the byte-code if the variable is specified outside the cycle (but will be used in it) and the similar binary code for the situation when the announcement took place in the cycle, it turns out that they absolutely the same!
Now the key question. Given all the above, what is really happening?