Looping
Loops in Java are used to execute a block of code repeatedly as long as a specified condition is met. Java provides several types of loops to cater to different looping requirements. Here are the main types of loops in Java, along with explanations and examples:
1. for
Loop:
for
Loop:The for
loop is used when you know in advance how many times you want to loop.
Syntax:
Example:
Explanation:
The
for
loop here runs fromi = 1
toi = 5
. In each iteration, it prints the message "Iterationi
" to the console.
2. while
Loop:
while
Loop:The while
loop is used when the number of iterations is not known beforehand, but the loop continues as long as a specified condition is true.
Syntax:
Example:
Explanation:
The
while
loop here starts withi = 1
. It continues to iterate and print the message as long asi
is less than or equal to5
.
3. do-while
Loop:
do-while
Loop:The do-while
loop is similar to the while
loop, but the condition is evaluated after the loop body, ensuring that the loop executes at least once.
Syntax:
Example:
Explanation:
In the
do-while
loop, the message is printed andi
is incremented inside the loop. The loop will run at least once even if the condition is false initially.
These are the main types of loops in Java. They enable you to repeat code execution based on specific conditions, allowing for efficient and controlled iterations in your programs.
Last updated