Hi,
What is for ( : ) in java.i know what a loop is but lately when i am doing excercises these keep coming up
Example:** for(Field currentField : emp.getClass().getDeclaredFields())**

it's the enhanced for loop.

String[] myStrings = {"one","two","three","four"};
for ( int i = 0; i < myStrings.length; i++ )
System.out.println(myStrings[i]`);

does the exact same as

String[] myStrings = {"one","two","three","four"};
for ( String tempString : myStrings )
System.out.println(tempString);

Yes. Instead of typing the declaration/initialization, condition and increment/decrement, you just go through two steps.

so its used mainly in arrays?

No, not just arrays. Anything that can iterate - including Sets, Lists etc

> ArrayList<String> myStrings = ... etc
> for ( String tempString : myStrings ) // works just like for arrays etc
>     System.out.println(tempString);

in fact it's more useful with Collection objects because the old-fashioned loop is harder to code and get right.

ps it's called a "for-each" loop, becuase when youy read it out loud you say "for each String s in myStrings..."

Edited 4 Years Ago by JamesCherrill

This question has already been answered. Start a new discussion instead.