• 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Final modifier in enhanced for-loop : How can this be?

 
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Enthuware question:

Identify the valid for loop constructs assuming the following declarations:



We have to select two options

1. for(o : c){ }
2. for(final Object o2 :c){ }
3. for(int i : ia) { }
4. for(Iterator it : c.iterator()){ }
5. for(int i : ia[0]){ }



I can understand how option 5 is correct; ia is an array of arrays, and the enhanced for-loop can traverse ia[0], which holds an array

How is option 2 correct? I thought that final in front of reference variable Object o2 means that once it points to an object on the heap, it does NOT point to ANOTHER object, otherwise you get compiler error. Yet, by traversing collection c, final Object o2 is pointing to DIFFERENT objects in the collection.

Please explain.
 
author
Posts: 23912
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sandra Bachan wrote:
How is option 2 correct? I thought that final in front of reference variable Object o2 means that once it points to an object on the heap, it does NOT point to ANOTHER object, otherwise you get compiler error. Yet, by traversing collection c, final Object o2 is pointing to DIFFERENT objects in the collection.

Please explain.



The final keyword, when it is used to specify the loop variable of the enhanced for-loop, means that the variable can't be changed during each iteration of loop.

Henry
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic