0

I came across a code snippit from my textbook with a : symbol.

for  (String arg : arg){
    System.out.println(arg);
}

I'd like to know what that : is, and what function it serves.

Thanks,

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by JamesCherrill
0

Probably a typo - should be: for (String arg : args){

It's a "for each" loop, introduced in Java 1.5. You read it as
"for each String arg in args"
It sets arg to the first element of args and executes the following println code, it then sets it to the second element, executes the code again (etc etc). It's roughly equivalent to, but much neater than

String arg;
for (int i = 0; i < args.length; i++ ) {
  arg = args[i];
  System.out.println(arg);
}

It also works with any kind of Collection eg ArrayList in exactly the same way, and avoids the complexity and pitfalls of Iterators.

Edited by JamesCherrill: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.