This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes for each loop and final Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "for each loop and final" Watch "for each loop and final" New topic
Author

for each loop and final

mayur dhawan
Greenhorn

Joined: Sep 20, 2005
Posts: 29
Hi,

I just came across this question.

for(final Object o : abc)
System.out.println(o);

I want to know why is this code working. The point of confusion is the final keyword.Is a new object reference is being created and destroyed in every iteration of the loop or what?

Please solve the question.

thanks in advance.
mayur
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6661
    
    5

It simply means you cannot modify the object reference after it has been set. Try this inside the loop - o = null;


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

This does seem odd at first, but it's explained in JLS 14.14.2 The enhanced for statement.

You will see that an enhanced for loop is equivalent to a regular for loop in which the iteration mechanism (either an Iterator or a counter based on an array's length) is part of the loop parameters, but the variable modifiers (like "final") are actually within the loop body. So in this case, "final" applies only within each iteration.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: for each loop and final
 
Similar Threads
The use of static and final.
A quetion of Garbage Collection
Final modifier in enhanced for-loop : How can this be?
Iterating arraylist over arrays
Using for..each loop on Object[]