Introduction to Loops
Loops in Java are used to execute a block of code repeatedly based on a condition. Java provides several types of loops, each suited for different scenarios.
1. For Loop
The for loop is used when you know exactly how many times you want to execute a block of code.
Basic Syntax
for (initialization; condition; increment/decrement) {
// code block to be executed
}
Examples of For Loop
Simple Counter
// Counting from 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println("Count is: " + i);
}
Counting Backwards
// Counting down from 10 to 1
for (int i = 10; i >= 1; i--) {
System.out.println("Countdown: " + i);
}
Iterating Over Array
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + " is: " + numbers[i]);
}
Using Different Step Values
// Counting by twos
for (int i = 0; i <= 10; i += 2) {
System.out.println("Even number: " + i);
}
2. Enhanced For Loop (For-Each)
The enhanced for loop is specifically designed to iterate over arrays and collections.
Basic Syntax
for (dataType item : array/collection) {
// code block to be executed
}
Examples of Enhanced For Loop
Iterating Over Array
String[] fruits = {"Apple", "Banana", "Orange", "Mango"};
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
Iterating Over ArrayList
import java.util.ArrayList;
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
for (Integer num : numbers) {
System.out.println("Number: " + num);
}
3. While Loop
The while loop executes a block of code as long as a condition is true.
Basic Syntax
while (condition) {
// code block to be executed
}
Examples of While Loop
Basic Counter
int count = 1;
while (count <= 5) {
System.out.println("Count is: " + count);
count++;
}
Input Validation
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int number = 0;
while (number <= 0) {
System.out.println("Enter a positive number: ");
number = scanner.nextInt();
}
System.out.println("You entered: " + number);
4. Do-While Loop
The do-while loop executes a block of code at least once before checking the condition.
Basic Syntax
do {
// code block to be executed
} while (condition);
Examples of Do-While Loop
Basic Counter
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 5);
Menu System
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\nMenu:");
System.out.println("1. Option One");
System.out.println("2. Option Two");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("You selected Option One");
break;
case 2:
System.out.println("You selected Option Two");
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice!");
}
} while (choice != 3);
5. Nested Loops
Loops can be nested inside other loops to create more complex iterations.
Examples of Nested Loops
Multiplication Table
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
Pattern Printing
// Printing a triangle pattern
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
6. Loop Control Statements
Break Statement
Used to exit a loop prematurely.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit loop when i equals 5
}
System.out.println("Number: " + i);
}
Continue Statement
Used to skip the current iteration and continue with the next one.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip printing when i equals 3
}
System.out.println("Number: " + i);
}
7. Common Use Cases and Best Practices
1. Iterating Over Collections
List<String> items = Arrays.asList("Item1", "Item2", "Item3");
for (String item : items) {
System.out.println(item);
}
2. File Processing
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
3. Input Validation
Scanner scanner = new Scanner(System.in);
int input;
do {
System.out.print("Enter a number between 1 and 10: ");
input = scanner.nextInt();
} while (input < 1 || input > 10);
Best Practices
- Choose the appropriate loop type for your needs
- Always use braces {} even for single-line loop bodies
- Be careful with loop conditions to avoid infinite loops
- Initialize counter variables properly
- Use meaningful variable names for loop counters
- Consider using enhanced for loop when possible
- Be cautious with nested loops as they can impact performance
Remember to always include a way to exit your loops and to test your loop conditions thoroughly to prevent infinite loops.