1. However, you CANNOT create same name variables within same scope in java.
2. About declaring same variable inside loop. This is called variable shadowing:
variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. At the level of identifiers (names, rather than variables)
Scope of Variables In Java
public class Test
{
// All variables defined directly inside a class
// are member variables
int a;
private String b;
void method1() {
// Local variable (Method level scope)
int x;
}
int method2() {....}
char c;
}
In your case,
after each loop, the scope is destroyed, and the variable is gone. In the next loop, a new scope is created, and the variable can be declared again in that scope.
With this:
for(int i=0; i<5; i++){
ArrayList<Integer> myList = new ArrayList<>();
}
A new block is created on every iteration. And there is only 1 variable named myList in each block.
Refer here
myListgoes out of scope at the end of each turn through the loop.()in your variable declarations.