Java Tutorial/Control Structures II - Looping

You can use loops to repeat the execution of a certain thing, without writing it out multiple times. There are several different loops you can use to meet your needs.

While Loops

edit

While loops are the simplest kind of loops. They go as follows:

while(boolean) {
    //Java code...The do section
}

While the boolean is true, the "do..." section will be executed. Once it becomes false, the loop will exit. An example:

int counter = 0;
while(counter < 5) {
    System.out.println(counter);
    counter++; //same as counter = counter + 1;
}
System.out.println(counter);

This displays the numbers 0 - 4 in the loop, and 5 outside of it.

Do-While Loops

edit

Do-While loops have the structure like:

do {
    //Java code...
} while(boolean);

It will execute "do...", and then check if the boolean is true or false. Then, it repeats. This is just like a regular while loop, except it ensures the code is executed at least once. An example of its use:

double counter = 1.5; //double is just like a float, except stores more
do {
    counter += 1.0; //add 1 to counter
    System.out.println(counter);
} while(counter < 5.0);

This will print the numbers 2.5, 3.5, 4.5, and 5.5.

For Loops

edit

For loops are used mostly when you want counters in your loop. The structure is:

for(assign something a value; boolean; what to exec after each loop) {
    do...
}

The usual usage is:

//myNumber is just some number or variable that you want to count up to
for(int i = 0; i < myNumber; i++) { //increase by 1
    do...
}

As you can see, the loop first sets i to equal 0. Then, it checks that i is less than myNumber (before actually executing something). Then, it executes "do...". It increases i by 1. Then, it checks that i is less than myNumber again, executes "do...", etc.

(learn for-each loops in array section?)

Exercises

edit
  • Make a for-loop that prints "Something" exactly 5 times.

Answer:

public class RegularAnswer {
    public static void main ( String[] args ) {
        for(int i = 0; i < 5; i++) { //can't be equal to 5, as i starts at 0
            System.out.println("Something");
        }
    }
}

Another, more "wild" answer:

public class WildAnswer {
    public static void main( String[] args ) {
        for(int i = 10; i < 18; i += 2) { //going by 2 each time, from 10 - 16
            System.out.println("Something"); //executed when i is 10, 12, 14, and 16
        }
        System.out.println("Something"); //5th time
    }
}
Previous: Control Structures I - Decision structures Up: Java Tutorial Next: Methods