aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Usage of Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Badass: Making Users Awesome this week in the Game Development forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Usage of "final" in enhanced for loop." Watch "Usage of "final" in enhanced for loop." New topic

Usage of "final" in enhanced for loop.

Sai Surya
Ranch Hand

Joined: Feb 08, 2006
Posts: 462

Hi All,

Here is my programme which is compiling and working fine.

public class EnhancedForTest {
public static void main(String... args) {
String[] strArr = {"A", "B", "C", "D"};

for (final String s : strArr) {

Since the String s is delcared as final, this code should not compile. However, this is working fine. Is it creating a new string object for every iteration because assignment is not possible second time for final variables?

Thanks & Regards,
- Surya.

Sai Surya, SCJP 5.0, SCWCD 5.0, IBM 833 834, I believe in Murphy's law.
Santhosh Raje

Joined: Sep 26, 2006
Posts: 9
Hi Sai,
The Final Reference Variable which is pointed to String array object is not changed.So no error occurs.Since I dont know how the for each method is internally implemented I cant say anything beyond this.
I agree. Here's the link:
subject: Usage of "final" in enhanced for loop.