• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

enhanced for loop

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Can somebody explain to me why the folowing code does not compile?
\
Why am I not allowed to declare the variable before the for statement? A normal for loop allows you this.

Thanks,
Valentn
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is from the Java Language Specification 14.14.2

14.14.2 The enhanced for statement
The enhanced for statement has the form:


EnhancedForStatement:
for ( VariableModifiersopt Type Identifier: Expression) Statement

The Expression must either have type Iterable or else it must be of an array type (�10.1), or a compile-time error occurs.


Note the Type is not optional.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So on one level, the answer is "because the rules say so". On another level, why did they write the rules this way? Well, the enhanced for loop is really just a shortcut for a couple very common lops of loops. The enhanced for loop doesn't have to enable you to do everything that a normal for loop can, because after all you can always go back to using a regular for loop. They just want to support the most common cases here. And the vast majority of the time, there's no need to declare the variable outside the loop. In fact, often this is just an added potential source of bugs, as it exposes the variable to a larger scope than it really needs, increasing the chance of name collisions or of using the wrong variable name. A good discussion of this can be found in Effective Java pp. 141-4: Minimize the scope of local variables.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic