Loops are used in Java to execute a block of code repeatedly. There are three primary types of loops in Java:
for
Loop
The for
loop is used when you know in advance how many times you want the loop to run. It consists of three parts:
The following example demonstrates how to print numbers from 1 to 5 using a for
loop:
public class ForLoopExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { System.out.println(i); } } }
while
Loop
The while
loop is used when you donβt know how many times you need to loop. The condition is evaluated before each iteration. The loop continues as long as the condition is true.
Here's an example of using a while
loop to print numbers from 1 to 5:
public class WhileLoopExample { public static void main(String[] args) { int i = 1; while (i <= 5) { System.out.println(i); i++; } } }
do-while
Loop
The do-while
loop is similar to the while
loop, but the condition is checked after the code block has executed. This means the code inside the do
block is always executed at least once.
In this example, the loop will print the numbers from 1 to 5:
public class DoWhileLoopExample { public static void main(String[] args) { int i = 1; do { System.out.println(i); i++; } while (i <= 5); } }
- **For loop**: Best when you know how many times you need to iterate. - **While loop**: Best when the condition may change during execution and you donβt know how many iterations are needed. - **Do-While loop**: Ensures that the code block is executed at least once, even if the condition is false initially.
You can use loops inside other loops. This is called a "nested loop." Hereβs an example of a nested for
loop to print a multiplication table:
public class NestedLoopExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) { System.out.print(i * j + " "); } System.out.println(); } } }
An infinite loop occurs when the condition of the loop is always true. Hereβs an example:
public class InfiniteLoop { public static void main(String[] args) { while (true) { System.out.println("This is an infinite loop!"); } } }
Practice Challenge: Write a program using a loop to sum all the even numbers from 1 to 100.
for
loop is useful when the number of iterations is known in advance.while
loop is better when the number of iterations is not known.do-while
loop ensures that the block of code is executed at least once.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!