Mastering Java Loops: A Comprehensive Guide
Java loops are a fundamental concept in programming, allowing you to execute a block of code repeatedly. In this article, we’ll explore the for
loop, its syntax, and various examples to help you understand its usage.
What is a Java for
Loop?
A Java for
loop is used to run a block of code for a specified number of times. Its syntax consists of three main components:
- Initialization: Initializes and/or declares variables, executed only once.
- Condition: Evaluated after initialization, determines whether the loop body is executed.
- Update: Updates the value of the initialization variable.
The process continues until the condition becomes false.
Example 1: Displaying Text Five Times
java
for (int i = 0; i < 5; i++) {
System.out.println("Hello");
}
This program will print “Hello” five times.
Example 2: Displaying Numbers from 1 to 5
java
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
This program will print numbers from 1 to 5.
Example 3: Calculating the Sum of Natural Numbers
java
int sum = 0;
for (int i = 1; i <= 1000; i++) {
sum += i;
}
System.out.println(sum);
This program calculates the sum of natural numbers from 1 to 1000.
Java for-each
Loop
The Java for
loop has an alternative syntax for iterating through arrays and collections.
java
int[] numbers = {3, 7, 9, 2};
for (int number : numbers) {
System.out.println(number);
}
This program prints each element of the numbers
array.
Infinite for
Loop
If the test expression never evaluates to false, the loop will run indefinitely.
java
for (int i = 0; i <= 10; ) {
System.out.println("Hello");
}
This program will print “Hello” repeatedly until the memory runs out.
Key Takeaways
- Java
for
loops are used to execute a block of code repeatedly. - The loop consists of initialization, condition, and update components.
- The
for-each
loop is an alternative syntax for iterating through arrays and collections. - Infinite loops can occur if the test expression never evaluates to false.