Line At A Time
Lesson 17: For Loop
For Loop Visit every item in an array, one by one.
1public static void main(String[] args) {
2 String[] arr = {"hello", "world", "!"};
3 for (int i = 0; i < arr.length; i++) {
4 System.out.println(arr[i]);
5 }
6}
Terminal
$ javac Main.java
$ java Main
hello
world
!
Every line, explained
public static void main(String[] args) {
Every Java program starts at the main method. When you run the program, Java looks for this exact line, public static void main(String[] args), and runs everything between its { and } from top to bottom.
String[] arr = {"hello", "world", "!"};
String[] declares an array of text values; the items go between curly braces, each in its own double quotes.
for (int i = 0; i < arr.length; i++) {
A for loop repeats code. Its three parts are separated by semicolons: int i = 0 creates the counter, i < arr.length keeps looping while that is true, and i++ adds 1 to the counter after every trip. Note that arr.length has no parentheses: for arrays, length is a built-in value, not a method.
System.out.println(arr[i]);
System.out.println(...) prints whatever is inside the parentheses to the terminal, then moves to a new line. Read the name carefully: print-l-n is short for "print line". On each trip around the loop, i is different (0, then 1, then 2), so arr[i] prints a different item each time.
}
This } closes the for loop. Everything between the loop's { and } is repeated on every trip around the loop.
}
This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.