Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why are there two different kinds of for loops in java?

Tags:

java

for-loop

I have a for loop, and I am not sure how it works. I am familiar with:

for(int i = 0; i <= 9; i++) {     /* implementation */ } 

I am confused about a for loop in the following form:

String[] myString = new String[] {"one", "two", "three", "some other stuff"};  String str1 = "", str2 = "";    for (String s :  myString) {     /* implementation */ } 

How do these types of for loops work? what do they do differently then regular for loops?

like image 286
Ephraim Avatar asked May 01 '11 20:05

Ephraim


People also ask

What are the two types of loops in Java?

In Java, there are three kinds of loops which are – the for loop, the while loop, and the do-while loop. All these three loop constructs of Java executes a set of repeated statements as long as a specified condition remains true.

How many types of for loops in Java?

In Java, there are three types of loops.

What are 2 types of loops?

There are two types of loops, “while loops” and “for loops”. While loops will repeat while a condition is true, and for loops will repeat a certain number of times. You'll also learn about for each loops which are a type of for loop that repeats once for each item in a list.


2 Answers

The first is the original for loop. You initialize a variable, set a terminating condition, and provide a state incrementing/decrementing counter (There are exceptions, but this is the classic)

For that,

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

is correct.

For Java 5 an alternative was proposed. Any thing that implements iterable can be supported. This is particularly nice in Collections. For example you can iterate the list like this

List<String> list = ....load up with stuff  for (String string : list) {   System.out.println(string); } 

instead of

for (int i=0; i<list.size();i++) {   System.out.println(list.get(i)); } 

So it's just an alternative notation really. Any item that implements Iterable (i.e. can return an iterator) can be written that way.

What's happening behind the scenes is somethig like this: (more efficient, but I'm writing it explicitly)

Iterator<String> it = list.iterator(); while (it.hasNext()) {   String string=it.next();   System.out.println(string); } 

In the end it's just syntactic sugar, but rather convenient.

like image 98
MJB Avatar answered Sep 24 '22 12:09

MJB


There is an excellent summary of this feature in the article The For-Each Loop. It shows by example how using the for-each style can produce clearer code that is easier to read and write.

like image 23
Greg Hewgill Avatar answered Sep 21 '22 12:09

Greg Hewgill