In Java, a loop is a feature used to execute a particular part of the program repeatedly if a given condition evaluates to be true. There are three types of loops in Java: for loop, while loop, and do-while loop. A for loop is used to iterate a given set of statements multiple times, and it is recommended to use it if the number of iterations is fixed. The syntax of a for loop is as follows:
for (initializationExpression; testExpression; updateExpression) {
// body of the loop
}
- The
initializationExpression
initializes and/or declares variables and executes only once. - The
testExpression
is evaluated for each iteration of the loop. If it is true, the body of the loop is executed. If it is false, the loop terminates. - The
updateExpression
is executed after the body of the loop has been executed.
For loops are best used when you know how many iterations you want to loop before you begin. On the other hand, while loops are used when you dont know the number of iterations.