🚀 Day 5: My Java Learning Journey 🚀
Today, I learned about looping statements, their various types, and the use of break and continue in Java. 📚🔄
These concepts are fundamental for controlling loops and optimizing code execution. 💡 Excited to keep building my Java skills!
Looping Statement: -
In Java, there are three types of loops:
Do-while loop:
Syntax:
do { // code to executed
//Update statement
} while (condition);
condition: it is an expression which is tested. if the condition is true, the loop body is executed and control goes to update expression. As soon as the condition becomes false, loop breaks automatically.
EG: i<=10
update Expression: Every time the loop body is executed, the this expression increments or decrements loop variable.
EG: i++
Example program for Do-while Loop:
While loop: -
Syntax:
while (condition) {
// code block to be executed
update-expression
}
Test Expression: In this expression, we have to test the condition. if the condition evaluates to true then we will execute the body of the loop and go to update expression. otherwise, we will exit from while loop.
Example: i<=10
Update Expression: After executing the loop body , this expression increments/decrements the loop variable by some value.
Example: i++;
Example program for While loop: -
For loop: -
Syntax:
for (initialization; condition; increment/decrement)
{
// statement or code block to be executed
}
Initialization: The initialization initializes and/or declares variables and executes only once.
condition: The condition is evaluated. if the condition is true, the body of the for loop is executed.
Increment/decrement: It increments or decrements the variable value. it is an optional condition.
Recommended by LinkedIn
Statement: The statement of the loop is executed each time until the second condition is false.
Example Program for For Loop:
Nested for Loop:
Syntax:
Nested For loop
for ( initialization; condition; increment )
{
for ( initialization; condition; increment )
{
// statement of inside loop
}
// statement of outer loop
}
Example Program for Nested Loop: -
For-Each Loop:
A for-each loop is a loop that can only be used on a collection of items. It will loop through the collection and each time through the loop it will use the next item from the collection. It starts with the first item in the array (the one at index 0) and continues through in order to the last item in the array.
Syntax:
for (type variableName : arrayName) { // code block to be executed }
Example Program for For-Each Loop: -
Break Statement: -
Syntax:
break;
Example Program for Break Statement: -
Continue statement: -
Syntax:
continue;
Example Program for Continue Statement: -
As you can see in the above output, 3 is not printed. It is because the loop is continued when it reaches to 3.