Why does the local variable of an enhanced for loop have to be local? [duplicate]

Look at how the for-each loop internally works, see How does the Java ‘for each’ loop work?

for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}

Each time it declares the String variable item. Hence in your case its doing essentially

State state;
\\and inside
State state = i.next();

which obviously wont work. Now inside the implementation, they it could rather only do

item = i.next();

but then you always have to define that item outside for-each, which would be pain majority of time.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)