| 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: 6588
|
|
|
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 - SCJP Mocks - SCJP 5 Mock exam (Word document ) - SCJP 5 Mock exam in Java.Inquisition format
|
 |
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
|
 |
 |
|
|
subject: for each loop and final
|
|
|