Coding for All
Lesson 19: For Loop Booleans
For Loop Booleans Combine a loop with an if statement.
1public static void main(String[] args) {
2 boolean[] arr = {true, true, false};
3 for (int i = 0; i < arr.length; i++) {
4 if (arr[i]) {
5 System.out.println("arr[" + i + "] is true");
6 }
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 of true/false values.
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.
if (arr[i]) {
if checks the condition inside its parentheses. If the condition is true, Java runs the code between the { and }. If it is false, Java skips that code completely. The condition is arr[i], whichever boolean the loop is currently visiting.
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". The + glues text and the number i into one message, e.g. "arr[" + 0 + "] is true" becomes arr[0] is true.
}
This } closes the if block.
}
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 }.