File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "for each loop and final" Watch "for each loop and final" New topic

for each loop and final

mayur dhawan
Ranch Hand

Joined: Sep 20, 2005
Posts: 30

I just came across this question.

for(final Object o : abc)

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.
Deepak Bala

Joined: Feb 24, 2006
Posts: 6662

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

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
I agree. Here's the link:
subject: for each loop and final
It's not a secret anymore!