Back to Java
2026-03-016 min read

Bash Loops (Java)

Learn Bash Loops (Java) step by step with clear examples and exercises.

Why This Matters

Understanding how to use loops effectively in Java is crucial for writing efficient and concise code, especially when dealing with large datasets or repetitive tasks. Knowing the differences between various loop types will help you choose the right one for each specific situation, improving your problem-solving skills and making you a better programmer.

Prerequisites

Before diving into Java loops, make sure you have a good understanding of basic Java concepts such as variables, data structures, and control structures like if and else statements. Familiarity with shell scripting is not required but may help you understand the motivation behind implementing similar loop constructs in Java.

Basic Java Concepts

  • Variables (primitive types: int, float, double, char, boolean; reference types: String, arrays, classes)
  • Data structures (arrays, lists, sets, maps)
  • Control structures (if, else if, else, switch)

Core Concept

Java provides four types of loops:

  1. For Loop: Used for iterating a fixed number of times or over a range of values.
  2. While Loop: Used for repeating a block of code as long as a certain condition is true.
  3. Do-While Loop: Similar to the while loop, but the code block is executed at least once before checking the condition.
  4. For-Each Loop (Enhanced For Loop): Used for iterating over collections like arrays and lists.

Let's examine each loop type with examples.

For Loop

The for loop is used when you know exactly how many times you need to execute the code block. It can be used to iterate through an array or a range of numbers.

int[] numbers = {1, 2, 3, 4, 5};

for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}

In this example, we have an array of integers called numbers. The for loop iterates from 0 to the length of the array and prints each number on a new line.

While Loop

The while loop continues executing as long as the specified condition is true.

int i = 1;

while (i <= 5) {
System.out.println(i);
i++;
}

In this example, we start with i equal to 1 and continue printing its value as long as it is less than or equal to 5, incrementing i after each iteration.

Do-While Loop

The do-while loop guarantees that the code block will be executed at least once before checking the condition. This can be useful when you want to ensure that a user enters valid input or perform some initialization before starting the loop.

Scanner scanner = new Scanner(System.in);
int i;

do {
System.out.print("Enter a number between 1 and 5: ");
if (scanner.hasNextInt()) {
i = scanner.nextInt();
break;
} else {
System.out.println("Invalid input. Please enter an integer.");
}
} while (i <= 0 || i > 5);

In this example, we use a do-while loop to prompt the user for input until they provide a valid number between 1 and 5. The loop will always execute at least once, even if the user enters invalid input initially.

For-Each Loop (Enhanced For Loop)

The for-each loop is used when you want to iterate over elements in an array or a collection like a list without keeping track of an index.

int[] numbers = {1, 2, 3, 4, 5};

for (int number : numbers) {
System.out.println(number);
}

In this example, we use the for-each loop to iterate over each element in the numbers array and print its value on a new line.

Worked Example

Let's write a Java program that calculates the sum of all even numbers between 1 and 100 using a for loop and a while loop for comparison.

int sum = 0;

// Using a for loop
for (int i = 2; i <= 100; i += 2) {
sum += i;
}
System.out.println("Sum using for loop: " + sum);

// Using a while loop
int evenNumber = 2;
sum = 0;

while (evenNumber <= 100) {
sum += evenNumber;
evenNumber += 2;
}
System.out.println("Sum using while loop: " + sum);

In this example, we calculate the sum of all even numbers between 1 and 100 using both a for loop and a while loop. The output will be the same for both loops:

Sum using for loop: 2500
Sum using while loop: 2500

Common Mistakes

  1. Forgetting to initialize counter variables: Make sure to set initial values for loop counters before starting the loop, especially when using a for loop or a while loop with an initial condition.
  1. Infinite loops: Be careful not to create infinite loops by setting conditions that will never be met. This can happen if you forget to increment or decrement the counter variable correctly.
  1. Not breaking out of loops: If you're using nested loops, make sure to use a break statement when a specific condition is met so that you don't continue iterating unnecessarily.
  1. Using the wrong loop type: Choose the appropriate loop type for your needs based on the number of iterations and whether you need to iterate over a collection or a range of values.

Common Mistakes (Continued)

  1. Not handling exceptions: Make sure to handle exceptions when working with user input, such as NumberFormatException when trying to convert Strings to numbers.
  1. Misunderstanding the scope of variables: Be aware that the scope of a variable can affect how it's accessed within nested loops or methods.

Practice Questions

  1. Write a Java program that calculates the sum of all odd numbers between 1 and 50 using a for loop and a while loop for comparison.
  1. Write a Java program that finds the largest prime number less than or equal to 100 using a for loop.
  1. Write a Java program that prints the Fibonacci sequence up to the 10th term using a for loop.

FAQ

What is the difference between a for loop and a while loop in Java?

The main difference lies in how they handle iteration. A for loop initializes, conditions, and increments/decrements are all defined within the loop declaration, making it more concise when iterating over a specific range of values or an array. On the other hand, a while loop checks the condition before each iteration, making it suitable for situations where the number of iterations is not known in advance or when dealing with user input.

Can I use a for-each loop to iterate through arrays?

Yes, you can use a for-each loop (also known as an enhanced for loop) to iterate through arrays and collections in Java. The syntax involves using the colon : operator instead of traditional indexing.

What happens if I don't include a break statement in a nested loop?

If you don't include a break statement in a nested loop, the outer loop will continue iterating even after the inner loop has found the desired condition. This can lead to unnecessary computations and potentially infinite loops if not handled carefully.

What is the difference between a do-while loop and a while loop?

The main difference between a do-while loop and a while loop is that the code block in a do-while loop executes at least once before checking the condition, whereas a while loop might not execute its code block if the initial condition is false. This makes the do-while loop useful for situations where you need to perform some initialization before checking the condition.

Bash Loops (Java) | Java | XQA Learn