Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

For loop question  RSS feed

 
Quang Pham
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I've not seen this for statement before.
How should I read this for statement:
for (String arg: args) {
argString += arg + " ";
}
Thanks
Quang
 
Nicholas Jordan
Ranch Hand
Posts: 1282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for (String arg: args)// for each element in args
{//enter code block
argString//some varaiable which is probaly a string
+= // gets appended
arg// the original string
+ // gets appended with:
" "// a single space (as a string)
;// ends the statement that will be done repeatedly
}// ends the code block

{ message edit: look at this: http://java.sun.com/docs/books/tutorial/collections/interfaces/collection.html }
[ November 06, 2007: Message edited by: Nicholas Jordan ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assume it's the "enhanced for" loop you're questioning. See For Each.

Basically, for (String arg : args) means for each String called "arg" in the array "args." It's a shorthand for...
 
Rob Spoor
Sheriff
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well it depends. If args is an array, then yes.

If args is a collection*, such as a list, it's shorthand for the following:



This shorthand is easier to write, easier to read and less error prone (like forgetting to call i.next()). There is one drawback: you loose the access to the current index, or the iterator. If you need either, because you're copying elements from one array to another, or you need the iterator's remove() method, you still have to write it out full.


* Well actually, and class that implements the new Iterable interface and therefore has an iterator() method.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rob Prime:
Well it depends. If args is an array, then yes...

You're right -- I made an assumption.
 
Quang Pham
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much. I guess it only work with the latest Java compiler.
 
Rob Spoor
Sheriff
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Already since Java 5, but not with 1.4 or earlier.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!