File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes New type of for loop? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "New type of for loop?" Watch "New type of for loop?" New topic

New type of for loop?

Tim Manchester
Ranch Hand

Joined: Nov 03, 2004
Posts: 62

I was perusing some code and I saw a for loop written in a way that I've never seen before. I was wondering if someone could explain this to me:

for (TransferLimit transferLimit : transferLimits)

This is not the typical for syntax that I'm used to. What is this?


vatsalya rao
Ranch Hand

Joined: Feb 14, 2007
Posts: 63
in this the variable "transferlimit"holds the values from th evariable "transferlimits"which are of type "Tranferlimit" .me too camt to know this recently from SUN site you too can refer to it from ""
Tim Manchester
Ranch Hand

Joined: Nov 03, 2004
Posts: 62
Thanks for the explanation & link. I've got it now.

Best Regards,

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15094

It is the new for-loop syntax which was introduced in Java version 5.0:
The For-Each Loop

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
gaurav abbi
Ranch Hand

Joined: Jan 05, 2007
Posts: 108
hi all,
i went to the link where explanation is given for using such kind of for syntax, there its also said,
"The for statement also has another form designed for iteration through Collections and arrays"

i'm not able to figure out how the loop will be used in case os collections for iteration, because normally wht we do is smthng like this

Iterator itr = list.iterator();


any code snippet about the new "for" syntax for using with collections
and why it should be preferred over current way of iteration.

thanks in advance.

thanks,<br />gaurav abbi
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
The new for syntax will automatically create an iterator for you.

However, using the new for syntax you will not be able to remove elements from the Collection. Also you will not be able to do anything that requires direct access to the iterator.

An example would be

The new for each loop makes the code more concise.
subject: New type of for loop?
It's not a secret anymore!