Click here to Skip to main content
16,019,018 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
public class EnhancedForTest {
  public static void main(String... args) {
    String[] strArr = {"A", "B", "C", "D"};

    for (final String s : strArr) {
      System.out.println(s);
    }
  }
}



Since the String s is delcared as final, this code should not compile. However, this is working fine. Why?

What I have tried:

there was nothing i could try !
Posted
Updated 22-Apr-19 7:14am

1 solution

Because the variable s is local to the for loop, so it is recreated at each iteration.
 
Share this answer
 
Comments
hiwa doski 22-Apr-19 14:10pm    
is this the same when you declare a variable in a normal for loop like -> for (int i=0; i<10;i++)
Richard MacCutchan 23-Apr-19 2:58am    
Yes, the variable i only exists within the for loop. Look up the Java scope rules for full details of the lifetime of variables and objects.
hiwa doski 24-Apr-19 8:08am    
Okay thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900