In the previous tutorial, we explored the while loop, which is used to execute a block of code repeatedly as long as a specified condition is true. In this tutorial, we will dive into another fundamental control structure in Java: the for loop. We'll also cover nested loops and the enhanced for-each loop, providing you with a comprehensive understanding of looping constructs in Java.
Loops are essential in programming as they allow us to repeat tasks without writing repetitive code. The for loop is one of the most commonly used loops in Java due to its concise syntax and versatility. Understanding how to use different types of loops will greatly enhance your ability to write efficient and effective Java programs.
The basic for loop in Java consists of three parts: initialization, condition, and update. It is typically used when the number of iterations is known beforehand.
1for (initialization; condition; update) {2// code block to be executed3};
true, the loop continues; if false, the loop terminates.Let's print numbers from 1 to 5 using a basic for loop.
1public class ForLoopExample {2public static void main(String[] args) {3for (int i = 1; i <= 5; i++) {4System.out.println(i);5}6}7}
1 2 3 4 5
A nested loop is a loop inside another loop. The inner loop will be executed completely for each iteration of the outer loop.
Let's print a multiplication table using nested for loops.
1public class NestedForLoopExample {2public static void main(String[] args) {3int rows = 5;4for (int i = 1; i <= rows; i++) {5for (int j = 1; j <= i; j++) {6System.out.print(j + " ");7}8System.out.println();9}10}11}
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
The for-each loop, also known as the enhanced for loop, is used to iterate over elements of an array or collection without using a traditional index.
1for (element : array) {2// code block to be executed3}
Let's print elements of an array using a for-each loop.
1public class ForEachLoopExample {2public static void main(String[] args) {3int[] numbers = {1, 2, 3, 4, 5};4for (int number : numbers) {5System.out.println(number);6}7}8}
1 2 3 4 5
Let's create a program that calculates the factorial of a number using a for loop.
1public class FactorialExample {2public static void main(String[] args) {3int number = 5;4long factorial = 1;5for (int i = 1; i <= number; i++) {6factorial *= i;7}8System.out.println("Factorial of " + number + " is: " + factorial);9}10}
Factorial of 5 is: 120
| Concept | Description |
|---|---|
| Basic For Loop | Executes a block of code repeatedly based on a condition. |
| Nested Loops | Allows one loop to be inside another, useful for multi-dimensional structures. |
| For-Each Loop | Simplifies iteration over arrays and collections without using indices. |
In the next tutorial, we will explore how to control the flow of loops using break and continue statements. These keywords provide more flexibility in managing loop execution based on specific conditions.
Stay tuned for more Java tutorials!