Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does "do" do here? (java)

I saw this bit of code on the interents somewhere. I'm wondering what the do is for.

public class LoopControl {
    public static void main(String[] args) {
        int count = 0;

        do {
            if (count % 2 == 0) {
                for (int j = 0; j < count; j++) {
                    System.out.print(j+1);

                    if (j < count-1) {
                        System.out.print(", ");
                    }
                }

                System.out.println();
            }

            count++;
        }
        while (count <= 5);
    }
}

By which I mean what exactly does do mean? What's its function? Any other information would be useful, too.

like image 227
David Avatar asked Apr 17 '10 21:04

David


People also ask

What is .do in Java?

The Java do-while loop is used to iterate a part of the program repeatedly, until the specified condition is true. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use a do-while loop.

What is the use of do while in Java?

Java do-while loop is used to execute a block of statements continuously until the given condition is true. The do-while loop in Java is similar to while loop except that the condition is checked after the statements are executed, so do while loop guarantees the loop execution at least once.

What is this and this () in Java?

In Java, both this and this() are completely different from each other. this keyword is used to refer to the current object, i.e. through which the method is called. this() is used to call one constructor from the other of the same class.

Do-while loop vs while loop Java?

The while loop in java executes one or more statements after testing the loop continuation condition at the start of each iteration. The do-while loop, however, tests the loop continuation condition after the first iteration has completed.


1 Answers

It is a do-while loop. So it will do everything in the following block while count is less than or equal to 5. The difference between this and a normal while loop is that the condition is evaluated at the end of the loop not the start. So the loop is guarenteed to execute at least once.

Sun tutorial on while and do-while.

Oh, and in this case it will print:

1, 2
1, 2, 3, 4

Edit: just so you know there will also be a new line at the start, but the formatting doesn't seem to let me show that.

like image 95
DaveJohnston Avatar answered Sep 28 '22 05:09

DaveJohnston