Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised January 9, 2026)

Previous: Basics

Loops

//
// Loops.java
//


// In this example we demonstrate two things:
//
// 1) for loops
//
// 2) conditional statements (if / else)
//

public class Loops
{
    public static void main(String[] args)
    {
        // the for loop declaration has 3 parts:
        //  initialization:     int i=0
        //  condition:          i<10
        //  update:             i++   (shorthand for i=i+1)
        //
        // the code in the body of the loop is executed
        // as long as the condition is true, applying the
        // update code after each iteration

        for (int i=0; i<10; i++)
        {
            // = is variable assignment
            // == is comparison (true or false)

            // || means or
            // && means and

            if (i%2 == 0)
            {
                System.out.println("Even");
            }
            else if (i == 7 || i == 3)
            {
                System.out.println("Lucky");
            }
            else
            {
                System.out.println(i);
            }
        }
    }
}

Output:

Even
1
Even
Lucky
Even
5
Even
Lucky
Even
9

Next: