A loop repeats a block. An enhanced for loop visits values in an array. A traditional for loop can work with an index. PDF Batch Studio later applies a rule to many CSV rows. First, we examine a small list so ordering and termination remain visible.
01Visit values
String[] describes an array containing text values. for (String name : names) sets name to the next value on each iteration. The colon belongs to this loop syntax.
public class Main {
public static void main(String[] args) {
String[] names = {"Ada", "Lin"};
for (String name : names) {
System.out.println(name);
}
for (int i = 0; i < names.length; i++) {
System.out.println((i + 1) + ": " + names[i]);
}
}
}
Run / check
java Main.java02Use indexes
The first index is 0. length describes the number of elements. i < names.length permits only existing indexes. i++ increments the counter.
03Understand stopping
break exits the loop. continue skips the remainder of the current iteration. A while loop needs a state change that eventually makes its condition false. Batch processing later adds an explicit cancellation signal.
Ada and Lin are printed in that order.
Your exercise
Add an empty name and skip it in the first loop.
Show the solution and explanation
Use if (name.isBlank()) { continue; } before println. isBlank also detects whitespace-only text. The second loop remains unchanged and demonstrates that the collection itself was not altered.
Project context and sources
The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.