• Post Reply Bookmark Topic Watch Topic
  • New Topic

Puzzler: Enhanced for loop using final  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just purchased the book and I'm about half way through it.. truly enjoying it! Coincidentally, I just discovered this puzzler while coding in Java 5, and was hoping for an explanation. An entire new edition of "Java Puzzlers..." could probably be written just based on the new features in Java 5! <hint, hint..> Here's a simplified example:



It seems counter-intuitive that even though the local variable element is declared final, you can use it to iterate through all of the int values in the array.
 
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This "final" declaration is all about scope. It seems for me that the variable will go out of scope at the end of the for loop and thus be redeclared in the next iteration. So it is not being reassigned, unlike the "usual" for:

In this case, "s" is not going out of scope at each iteration and therefore cannot be final.
But this brings me to another question: does this redeclaration approach affect performance?
 
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Henrique Sousa:
But this brings me to another question: does this redeclaration approach affect performance?

And you don't have an idea how to write a test?
 
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Henrique Sousa:

But this brings me to another question: does this redeclaration approach affect performance?


No, the declaration of a local variable is a noop at runtime.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!