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())**

Recommended Answers

All 4 Replies

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);

so its used mainly in arrays?

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..."

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.