File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

for each loop and final

 
mayur dhawan
Ranch Hand
Posts: 30
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It simply means you cannot modify the object reference after it has been set. Try this inside the loop - o = null;
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic