Java Loops Cheat Sheet

Quick reference for for/while/do-while/enhanced for loops in Java.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

For loop

Basic for loop

Loop from 0..4

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

Classic counted loop. Great when you need an index.

Loop N times

javaANYjavaloopsfor
java
for (int i = 0; i < n; i++) {
  // ...
}

Reverse loop

javaANYjavaloopsfor
java
for (int i = n - 1; i >= 0; i--) {
  // ...
}

Enhanced for (for-each)

Enhanced for (for-each)

Iterate values without index

javaANYjavaloopsforeach
java
for (String s : list) {
  System.out.println(s);
}

Use for-each when you don’t need the index.

While / do-while

while loop

javaANYjavaloopswhile
java
while (condition) {
  // ...
}

do-while loop

Executes body at least once

javaANYjavaloopsdo-while
java
do {
  // ...
} while (condition);

do-while always executes the body at least once.

More in Java

No other published sheets yet.

Recommended next

No recommendations yet.