The FOR Loop statement is a very useful looping statement in Java programming. A For loop can be used to repeatedly execute a statement until a condition is satisfied. The addition of the enhanced foreach syntax in Java 5 is also very useful.
1. For statement
The number of times the For loop executes is determined before execution. The syntax format is as follows:
for( initialize; Boolean expression; update ) { // code statement }
There are several explanations for the For loop:
- The initialization step is performed first. You can declare a type, but you can initialize one or more loop control variables, or you can be an empty statement.
- Then, the value of the Boolean expression is detected. If true, the loop body is executed. If False, the loop terminates, starting execution of the statement following the loop body.
- After the loop is executed, the loop control variable is updated.
- Re-detects the Boolean expression. The loop executes the above procedure.
2.foreach statements
The foreach statement is a special simplified version of the For statement, and the Foeeach statement does not completely replace the for statement, but any foreach statement can be rewritten as a version of the for statement. foreach is not a keyword, and it is customary to call this special for-statement format a foreach statement. The foreach statement provides a great convenience for programmers in traversing arrays, collections, and so on. The syntax format is as follows:
for (element variable x: Traversal object obj) {reference x Java statement}
An element variable in a foreach statement that does not have to be initialized. The data type of the element variable must be the same as the data type of the object obj.
You can also use the For loop combination to print a lot of interesting graphics. Like 99 multiplication table, all kinds of diamond ... Here is the diamond for the For loop exercise:
Java Learning for loop print diamond drills