Line At A Time
Lesson 20: While Loop
While Loop Loop for as long as a condition stays true.
1public static void main(String[] args) {
2 boolean[] arr = {true, true, false};
3 int i = 0;
4 while (arr[i]) {
5 System.out.println("arr[" + i + "] is true");
6 i++;
7 }
8}
Terminal
$ javac Main.java
$ java Main
arr[0] is true
arr[1] is true
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.
boolean[] arr = {true, true, false};
A boolean[] array; the last item is false, and that is what will stop our loop.
int i = 0;
int declares a variable that stores a whole number (an "integer") like 1, 5 or 1000. The = sign stores the value on the right into the variable named on the left, and the semicolon ; ends the statement, like a full stop at the end of a sentence. With a while loop you create the counter yourself, before the loop.
while (arr[i]) {
A while loop repeats its block for as long as the condition in the parentheses is true. The condition is checked again before every trip around the loop. Here the condition is arr[i]: the loop keeps going while the current item is true, and stops the moment it reaches arr[2], which is false.
System.out.println("arr[" + i + "] is true");
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". Prints which position was true, gluing the number i into the text.
i++;
i++ increases i by 1. It is a short way of writing i = i + 1; (you can also write i += 1;). Without this line, i would stay 0 and the loop would never end!
}
This } closes the while loop.
}
This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.