Loops Archive

Java Break and Continue in Loops

These two keywords help us control the loop from within it. break will cause the loop to stop and will go immediately to the next statement after the loop: continue will stop the current iteration and will move to the next one. Notice that inside a for loop, it will still run the third section.

Java Foreach Loop

Another version of for, is the foreach. The keyword we use is still for, but when we want to iterate on the elements inside an array we can simply use it: This is a short version and equivalent to: Notice that if you want to use the index of the element inside the loop, you have

Java While Loop

The syntax is very similar to the previous for we looked at: The condition will run for the first time when entering and every time the loop is done. If it returns false, the loop will not run. If we want the loop to always run at least one, we can use do-while Notice the ; in

Java For Loop

The for loop has three sections: First section runs once when we enter the loop. Second section is the gate keeper, if it returns true, we run the statements in the loop, if it returns false, we exit the loop. It runs right after the first section for the first time, then every time the loop is