AI Hints
Home›Java Tutorial›Counting and Summing, Infinite Loops and Off-by-One, Practice: Times Table
Java · Lesson 44 of 120

Infinite Loops and Off-by-One

Classic loop mistakes.

⏱ 2 min read▶ Video at 55:25🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Two mistakes catch almost every beginner. A loop that never stops, and a loop that runs one time too many, or one too few.

  • Never stops
  • One too many
  • One too few

Infinite loops

If the condition never becomes false, the loop runs forever. Usually, you forgot to change the counter. In a terminal, Control C stops a stuck program. Sometimes an endless loop is on purpose, with a break inside.

keyvalue
Causethe condition stays true
Oftenforgot i++
Stop itCtrl+C
On purposewhile (true) + break

while true, with a break

While true never ends on its own. So we leave it with break, when we find what we want. Here, we look for the first number whose square is over fifty. Run it. Eight times eight is sixty four.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int i = 0;
        while (true) {
            i++;
            if (i * i > 50) {
                break;
            }
        }
        System.out.println("First square over 50: " + i + " x " + i + " = " + i * i);
    }
}
Output
First square over 50: 8 x 8 = 64

Off by one

Less than five, and less than or equal to five, look almost the same. But one runs five times, and the other runs six. Run it. The second loop includes five. Always check, should the last value be included?

Main.javajava
public class Main {
    public static void main(String[] args) {
        System.out.print("i < 5:  ");
        for (int i = 0; i < 5; i++) System.out.print(i + " ");
        System.out.println();
        System.out.print("i <= 5: ");
        for (int i = 0; i <= 5; i++) System.out.print(i + " ");
        System.out.println();
    }
}
Output
i < 5:  0 1 2 3 4
i <= 5: 0 1 2 3 4 5

Summary

Make sure every loop can end. And check your boundaries, less than, or less than or equal. Next, a practice times table.

Key takeaways
  • Change the counter
  • Ctrl+C stops it
  • < or <=?
Next up: Practice: Times Table — put module five together