HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to JavaVariablesData TypesOperatorsStringsArraysLists (ArrayList)Conditions (if / switch)Loops (for / while)MethodsClasses (OOP)
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & List
🔁 Condition & Loop
🧩 Method & Class
Java›Loops (for / while)

Loops (for / while)

for for definite repetition, for-each for iteration, while for conditional repetition.

Simple enough for a 5-year-old to understand

for loop

Example code
1
public class Main {
2
public static void main(String[] args) {
3
for (int i = 1; i <= 3; i++) {
Initialization; condition; increment.
LoopInitialization; condition; increment.
4
System.out.println(i);
1, 2, 3
Output / Input1, 2, 3
5
}
6
}
7
}
LoopOutput / Input

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Print the numbers from 1 to 5 vertically using a for loop.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

There are four loop formats in Java: classic for, enhanced for, while, and do-while. Which one you choose depends on the task at hand, and the right choice makes the code significantly more readable.

The enhanced for — the format that iterates directly over arrays and collections — is preferred in most everyday code: there is no risk of an index error and it clearly shows intent. The classic for is needed when you need the index or are iterating backwards.

In modern Java, the stream API is also used to transform collections: it expresses filtering, mapping, and reduction operations without writing loops. It does the same job as loops but communicates intent more clearly.

What you will learn

  • The classic for loop and counter logic
  • Traversing arrays and lists with the enhanced for
  • The difference between while and do-while
  • Using break and continue
  • Nested loops and labeled break
  • How to avoid an infinite loop

When to use?

The enhanced for is the default choice when processing all elements of a collection. The classic for is used when an index is needed or the step is other than one.

do-while is used when the body MUST run AT LEAST ONCE: situations like showing a menu or asking for input until the user provides a valid one.

Common mistakes

Wrong

int[] nums = {1, 2, 3};
for (int i = 0; i <= nums.length; i++) {
    System.out.println(nums[i]);
}

Because less-than-or-equal is used in the condition, the loop runs one extra time and exceeds the array bounds on the last turn; you get an "ArrayIndexOutOfBoundsException". The condition in array loops must always be strictly less than.

Correct

int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++) {
    System.out.println(nums[i]);
}

Wrong

int i = 0;
while (i < 5) {
    System.out.println(i);
}

Since the counter never increments, the condition always stays true and the program enters an infinite loop. When using while, it is mandatory to ensure there is a change affecting the condition inside the loop.

Correct

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

Wrong

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

The semicolon at the end of the for line makes the loop body EMPTY; the block with curly braces runs once independently of the loop and gives a compilation error because i is not defined there. This is a syntax error that is hard to spot by eye.

Correct

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

Frequently asked questions

How do I choose between the enhanced for and the classic for?

If you only need the elements, use the enhanced for: it is shorter, more readable, and you cannot make an index error. If you need an index, are iterating backwards, or the step is other than one, the classic for is required.

What is the difference between while and do-while?

while checks the condition first; if the condition is false from the start, the body never runs. do-while runs the body once, then checks the condition. do-while is suitable for situations requiring "at least once", such as displaying a menu.

How do I break out of a nested loop in one go?

break only breaks the innermost loop it is inside. To break out of two loops at once, you can label the loop and use a labeled break. However, this reduces readability; in most cases, extracting the inner loop into a separate method and returning is a cleaner solution.

Summary

In Java, the enhanced for is the default way to traverse collections; the classic for is used when an index is needed. The top three mistakes: using less-than-or-equal in an array loop, forgetting to increment the counter inside a while, and putting a semicolon at the end of the for line.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code