Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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


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
Author

Usage of "final" in enhanced for loop.

Sai Surya
Ranch Hand

Joined: Feb 08, 2006
Posts: 460

Hi All,

Here is my programme which is compiling and working fine.

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

for (final String s : strArr) {
System.out.println(s);
}
}
}
</code>

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
http://sai-surya-talk.blogspot.com, I believe in Murphy's law.
Santhosh Raje
Greenhorn

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.
 
GeeCON Prague 2014
 
subject: Usage of "final" in enhanced for loop.