Comparing Java Loops


A way exists to code any looping need using any one of the three loop variants. The following test and three methods show three techniques for displaying a list of numbers separated by commas.

 public void testCommas() {    String sequence = "1,2,3,4,5";    assertEquals(sequence, sequenceUsingDo(1, 5));    assertEquals(sequence, sequenceUsingFor(1, 5));    assertEquals(sequence, sequenceUsingWhile(1, 5));    sequence = "8";    assertEquals(sequence, sequenceUsingDo(8, 8));    assertEquals(sequence, sequenceUsingFor(8, 8));    assertEquals(sequence, sequenceUsingWhile(8, 8)); } String sequenceUsingDo(int start, int stop) {    StringBuilder builder = new StringBuilder();    int i = start;    do {       if (i > start)          builder.append(',');       builder.append(i);    } while (++i <= stop);    return builder.toString(); } String sequenceUsingFor(int start, int stop) {    StringBuilder builder = new StringBuilder();    for (int i = start; i <= stop; i++) {       if (i > start)          builder.append(',');       builder.append(i);    }    return builder.toString(); } String sequenceUsingWhile(int start, int stop) {    StringBuilder builder = new StringBuilder();    int i = start;    while (i <= stop) {       if (i > start)          builder.append(',');       builder.append(i);       i++;    }    return builder.toString(); } 

As this example shows, you will find that one of the loop variants is usually more appropriate than the other two. Here, a for loop is best suited since the loop is centered around counting needs.

If you have no need to maintain a counter or other incrementing variable, the while loop will usually suffice. Most of the time, you want to test a condition each and every time upon entry to a loop. You will use the do loop far less frequently. The need to always execute the loop at least once before testing the condition is less common.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net