0

I have a question about for loops in java. I understand how for loops work an using the format :

for(initialize variable : condition : counter){}

My problem is in one of my lectures it says:

 for(String s : str){.....}

How come this doesn't need a counter? What is str?

Crazypigs
  • 87
  • 3
  • 13
  • 3
    This is an enhanced for loop, or a "for each" loop: https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with str should be a collection of strings in your example – vefthym Nov 08 '14 at 11:14

4 Answers4

2

This is an enhanced for loop, or a "for each" loop. It iterates over all the elements of str, which is probably a Collection of Strings in your example, or an Array of Strings.

Read this for more details.

For example, instead of writing this:

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

you can write its equivalent:

for (int myValue : myArray) {
    System.out.println(myValue);
}
vefthym
  • 7,422
  • 6
  • 32
  • 58
1

It is an enhanced for loop that iterates through every element in the Collection. It doesn't stop until it is has hit the last element or encounters a break;.

drhunn
  • 21
  • 1
  • 2
  • 13
1

First of all replace : with ; in the first for loop like this(you have used wrong syntax)

for(initialize variable ; condition ; counter){}

and the second one is the enhanced for loop,

for(String s : str){.....}

quite handy in case of the collections,It does not require any counter because it runs till it reaches the last element in the collection provided to it(In this case str is that collection)

See this to learn more about it What is the syntax of enhanced for loop in Java?

Community
  • 1
  • 1
nobalG
  • 4,544
  • 3
  • 34
  • 72
0

Your definitive source for this sort of questions is the Java Language Specification. In this particular case:

http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14

A more friendly source may be found in the official Java Tutorials, in this case:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

Jonathan Rosenne
  • 2,159
  • 17
  • 27