aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Final modifier in enhanced for-loop : How can this be? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Final modifier in enhanced for-loop : How can this be?" Watch "Final modifier in enhanced for-loop : How can this be?" New topic
Author

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

Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
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.


Marriage Made in Heaven
http://www.youtube.com/user/RohitWaliaWedsSonia
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18108
    
  39

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Final modifier in enhanced for-loop : How can this be?
 
Similar Threads
Confusion about array instance
Doubt in assertion
about Enhanced For loop
Array conversion Question from Dan's test
Can an arraylist hold null reference or not using add(Index i, Object obj) method?