🌊Loops
💡 Loops in Java In Depth with Rules for Each Loop 👨💻
👉 for Loop
The general structure of a for loop has three main parts:
Initialization - Here you define your loop counter variable (often an int i = 0) to track how many iterations have occurred
Condition - A Boolean expression that evaluates to true or false to determine whether the loop should continue running (i.e. i < 5)
Increment/decrement - What happens to your counter variable at the end of each iteration to eventually cause the condition to evaluate to false and exit the loop (i.e. i++ to add 1 to i each time, i+=2 to add 2 to each time )
The initialization step happens once before the loop starts, typically declaring and initializing a counter variable.
The condition is checked at the start of each iteration and the block will repeat as long as it evaluates to true.
After each iteration, the increment expression runs to modify the counter variable value for the next cycle.
Rules:
Initialization happens first and only once
Condition is evaluated before each iteration
Increment/decrement happens after each iteration
👉 while Loop
The general structure of a for loop has three main parts:
Condition - A Boolean expression that evaluates to true or false to determine whether the loop should continue running (i.e. i < 5)
Using while provides flexibility when you don't know ahead how many rounds are needed. It repeats as long as the scenario demands.
Rules:
Condition is evaluated before the loop body
Loop body executes as long as condition is true
Condition needs to eventually become false to avoid infinite loop
👉 do-while Loop
In a regular while loop, the condition check happens at the beginning of each iteration. So if the condition is false from the start, the loop body code inside the braces is skipped entirely and never runs even once.
In a do-while loop, the logic is reversed - the loop body runs first, and then the condition check occurs at the end.
This has an important implication. Even if evaluating the condition returns false the very first time after the loop body executes, the loop body code will have already run one time before the condition stops the loop.
Rules:
Loop body executes first, then condition is evaluated
Loop repeats as long as condition is true
Condition is evaluated after each iteration
👉 for-each Loop
A for-each loop is a cleaner way to iterate over elements in an array or collection compared to a regular for loop.
On each iteration, the Java compiler automatically takes the next element from arrayName and assigns it to variableName for us to use inside the loop body.
We don't have to declare or worry about an index counter variable like in a regular for loop.
Rules:
Used to iterate through elements of array or collection
Element takes on value of current element
Loop iterates till all elements are covered
Modifying element does not change array/collection
Loop mastery is key to efficient coding in Java!
Last updated