Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised September 1, 2025)

Previous: 3. Loops and Algorithms

HelloLoops

//
// HelloLoops.java
//


public class HelloLoops
{
    public static void main(String[] args)
    {
        System.out.println("Hello, loops!");
        System.out.println();

        // for loop:
        //
        // initialization:  int i = 0
        // condition: i<5
        // update: i++ 

        for (int i=0; i<5; i++)
        {
            System.out.println("for " + i);
        }

        System.out.println();

        // while loop
        
        int i = 0;

        while (i < 5)   // condition
        {
            System.out.println("while " + i);
            i++;
        }

        System.out.println();

        // do-while loop

        i = 0;

        do 
        {
            System.out.println("do-while " + i);
            i++;
        } while (i<5);  // condition checked at end

        System.out.println();

        // 'continue' moves to the next iteration
        // 'break' ends the loop

        for (int j=0; j<5; j++)
        {
            if (j == 1)
                continue;

            System.out.println("loop " + j);

            if (j == 3)
                break;
        }
    }
}

Output:

Hello, loops!

for 0
for 1
for 2
for 3
for 4

while 0
while 1
while 2
while 3
while 4

do-while 0
do-while 1
do-while 2
do-while 3
do-while 4

loop 0
loop 2
loop 3

Next: