Java Loops - The Coding Shala
Home >> Learn Java >> Java Loops
In Java, loops are used to execute the same set of code again and again until termination. There are three types of loops or iteration statements are for, while, and do-while.
Java while loop
The basic syntax of Java while loop is as follows:
The code inside the body of while loop will be executed as long as the condition is true. The condition can be any boolean expression.
The following Java program explains Java's while loop:
Java do-while loop
The basic syntax of Java's do-while loop is as follows:
The do-while loop always executes its body part at least once, because its condition is checked at the bottom of the loop.
The following Java program explains Java's do-while loop:
Java for loop
The basic syntax of Java's for loop is as follows:
Here, when the for loop starts the initialization expression is sets the value of the loop control variable. The condition must be a boolean expression and loop variables check whether the condition is true or not. If it is false, the loop terminates. Next, the iteration part is used to increments and decrements the loop control variables.
The following java program explains the for loop:
Note: we can declare the loop control variables inside the for a loop. We can also use more than one statement inside for loop using a comma(,) and semicolon(;) is used as separated.
Java For-Each loop
Java for-each loop is the enhanced version of for loop. The basic syntax of the for-each loop is as follows:
Here, var_name is the name of the iteration variable that will receive the elements from a collection from start to end one at a time of specified type.
The following Java program explains the for-each loop:
Other Posts You May Like