Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • 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.
 
Henry Wong
author
Marshal
Pie
Posts: 21507
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic