You are probably familiar with two types of Python loops: while and for. Java has both, but two types of for loops, for and for-each. We cover while and for loops here, then show for-each loops later.
Just like conditionals, methods, and all other compound statements, Java while loops use squiggly braces. Otherwise, they look very similar to Python while loops:
public static void main(String[] args) { System.out.println("Hello, World!"); String band = "garbage"; int index = 0; while (index < band.length()) { System.out.println(band.charAt(index)); index++; } }
$ javac *.java $ java CodeToRun Hello, World! g a r b a g e
We can simplify the above code using a for loop. This looks less like a Python for loop, and more like a modified while loop. Basically, instead of just putting the condition inside the parentheses, there are three full statements inside. Here's an example of the above code rewritten with for:
public static void main(String[] args) { System.out.println("Hello, World!"); String band = "garbage"; for (int index = 0; index < band.length(); index++) { System.out.println(band.charAt(index)); } }
Note the three parts inside the parentheses, separated by semicolons. The first part is the instantiation and is executed only once as the very first part of the loop. The second part is the condition we're familiar with: after each iteration, the loop only continues if the condition is true. The third part is the update; this line gets executed after each iteration of the loop finishes. If you ever have a while loop that looks like this: (A, B, X, Z, and C are some statements or expressions.)
public static void main(String[] args) { System.out.println("Hello, World!"); A; while (B) { X; ... Z; C; } }
...then you can rewrite the loop as:
public static void main(String[] args) { System.out.println("Hello, World!"); for (A; B; C) { X; ... Z; } }
In Python, you can use a for loop to traverse anything that's iterable, such as strings and lists. The Java version of this is a for-each loop, except that some things in Java aren't iterable. (Strings are an example of this!) We'll see examples of Java for-each loops after we talk about arrays.