Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
In Java, loops are used to execute a block of code repeatedly until a specified condition is met. One of the most commonly used loops is the for
loop. In this tutorial, we'll discuss the basics of the for
loop in Java and its variations.
The basic for
loop consists of three parts: initialization, condition, and increment/decrement. The loop begins with the initialization, then checks the condition, and if it evaluates to true, the code block is executed. After each iteration, the increment/decrement operation is performed, and the condition is checked again.
Syntax:
for (initialization; condition; increment/decrement) { // Code block to be executed }
Example:
public class ForLoopExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { System.out.println("Iteration " + i); } } }
In this example, the loop initializes the variable i
to 1, checks if i
is less than or equal to 5, and increments i
by 1 after each iteration. The loop will continue until i
is greater than 5.
Java introduced the enhanced for loop (also known as the for-each loop) in version 1.5, which is used to iterate over arrays and collections (e.g., ArrayList, HashSet, etc.). The enhanced for loop eliminates the need for an index variable and makes the code more readable.
Syntax:
for (type variable : array/collection) { // Code block to be executed }
Example:
public class EnhancedForLoopExample { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; for (int number : numbers) { System.out.println("Number: " + number); } } }
In this example, the enhanced for loop iterates over the numbers
array, assigning each element to the variable number
in each iteration.
A nested for loop is a for loop inside another for loop. Nested for loops are commonly used to work with multidimensional arrays or to perform repetitive operations multiple times.
Example:
public class NestedForLoopExample { public static void main(String[] args) { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { System.out.println("i: " + i + ", j: " + j); } } } }
In this example, the outer for loop iterates 3 times, and the inner for loop iterates 3 times as well, resulting in a total of 9 iterations.
In conclusion, the for
loop is a versatile control structure in Java that allows you to execute a block of code repeatedly based on a specified condition. The basic for loop provides a way to iterate with an index variable, while the enhanced for loop simplifies iteration over arrays and collections. Nested for loops enable complex, multi-level looping structures to be created.
Iterating through an array with for loop in Java
The traditional for loop allows you to iterate through elements in an array.
int[] numbers = {1, 2, 3, 4, 5}; for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + ": " + numbers[i]); }
Using the enhanced for loop in Java
The enhanced for loop simplifies the process of iterating through arrays or collections.
int[] numbers = {1, 2, 3, 4, 5}; for (int num : numbers) { System.out.println("Element: " + num); }
Nested for loops in Java
You can nest multiple for loops to iterate through multi-dimensional arrays or create complex patterns.
for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(i + "," + j + " "); } System.out.println(); }
Break and continue statements in Java for loop
The break
statement exits the loop prematurely, and the continue
statement skips the rest of the code in the current iteration.
for (int i = 0; i < 5; i++) { if (i == 3) { break; // Exit the loop when i is 3 } System.out.println("Iteration: " + i); }
Looping through a collection with for loop in Java
You can use the for loop to iterate through elements in a collection, such as an ArrayList.
List<String> fruits = Arrays.asList("Apple", "Banana", "Orange"); for (String fruit : fruits) { System.out.println("Fruit: " + fruit); }