I am playing around learning Lambda within Java and needed to create a list of variables. I created a for loop which creates a new String variable on each iteration, however each one has the same variable name which is not aloud outside of a for loop.
I see in the following post, Why is it allowed to declare a variable in a for loop? , they detail that its because of the scope of the created variable within the loop. However, I added the variable to an ArrayList outside of the scope of the for loop and then iterated through it to see that the duplicated name variables still exists with no errors.
I duplicated the code to have each variable have the same String value as well, to check if it had something to do with the values being different, but it still allowed the variables to be stored into the Array...
Code is below.
import java.util.ArrayList;
public class Lambda
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<String>();
for(int i = 0; i<10; i++)
{
String name = "name: ";
names.add(name);
}
names.forEach((name) -> {System.out.println(name);});
System.out.println("\n***********************************\n");
for(String temp: names)
{
System.out.println(temp);
}
}
}