Java for Loop [with Examples]

Java Tutorials

Summary: In this tutorial, you will learn how to use for loop in Java with the help of the exmaples.

Loops are an essential control flow mechanism in programming. They allow you to execute a block of code repeatedly, based on a condition. This can be useful in a variety of situations, such as:

  • Iterating over the elements of an array or a collection
  • Repeating an operation a specific number of times
  • Processing user input until a certain condition is met

For example, you might use a loop to read a series of numbers from the user and then calculate the average of those numbers. Or you might use a loop to process a list of files and perform some operation on each one. Loops can save you a lot of time and effort by automating repetitive tasks.

There are several types of loops available in Java, including:

  • for
  • while
  • and do-while.

Each of these loops has its own specific use cases, and you can choose the one that best fits your needs.

For Loop in Java

The for loop in Java is a control flow statement that allows you to iterate over a range of values. It has the following syntax:

for (initialization; condition; increment/decrement) {
   // code block to be executed
}

Here is an example of a for loop that iterates from 0 to 9:

for (int i = 0; i < 10; i++) {
   System.out.println(i);
}

This will output the numbers 0 through 9 to the console.

The initialization statement is executed before the loop starts. It is typically used to initialize the loop variable. In the example above, the loop variable i is initialized to 0.

The condition is checked before each iteration of the loop. If the condition evaluates to true, the code block within the loop is executed. If the condition evaluates to false, the loop terminates. In the example above, the condition is i < 10, so the loop will continue as long as i is less than 10.

The increment/decrement statement is executed after each iteration of the loop. It is typically used to update the loop variable. In the example above, the loop variable i is incremented by 1 after each iteration of the loop.

Example 1: Iterating over an array

You can also use the for loop to iterate over elements in an array or a collection. Here is an example of a for loop that iterates over the elements of an array:

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

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

This will output the elements of the numbers array to the console. You will learn about array in later posts.

Example 2: Counting from 0 to 9

for (int i = 0; i < 10; i++) {
   System.out.println(i);
}

This will output the numbers 0 through 9 to the console.

Example 3: Counting from 10 to 1

for (int i = 10; i > 0; i--) {
   System.out.println(i);
}

This will output the numbers 10 through 1 to the console.

For Each Loop in Java

The for-each loop is a variation of the for loop in Java that allows you to iterate over the elements of an array or a collection. It has the following syntax:

for (type element : array or collection) {
   // code block to be executed
}

Here is an example of a for-each loop that iterates over the elements of an array:

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

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

This will output the elements of the numbers array to the console.

The for-each loop is simpler to use than the standard for loop, because you don’t have to worry about the loop variable or the loop condition. The loop will iterate over all the elements of the array or collection automatically.

Here is an example of a for-each loop that iterates over the elements of a List:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

for (String name : names) {
   System.out.println(name);
}

This will output the elements of the names list to the console.

Note that the for-each loop is not suitable for cases where you need to modify the array or collection as you iterate over it. In those cases, you should use the standard for loop.

Infinite For Loop in Java

An infinite for loop is a loop that runs indefinitely, because the loop condition is always true. Here is an example of an infinite for loop:

for (;;) {
   // code block to be executed
}

This loop will never terminate, because the loop condition is always true.

Infinite loops are generally not a good idea, because they can cause your program to hang or crash. However, there are some cases where an infinite loop is useful, such as when you are waiting for user input or for some other event to occur. In those cases, you should include a break statement within the loop to allow it to terminate under certain conditions.

Here is an example of an infinite loop that terminates when the user enters a specific number:

Scanner scanner = new Scanner(System.in);

for (;;) {
   System.out.println("Enter a number (0 to exit):");
   int number = scanner.nextInt();
   if (number == 0) {
      break;
   }
   System.out.println("You entered: " + number);
}

System.out.println("Exiting loop.");

This loop will continue to read numbers from the user until the user enters 0, at which point it will exit the loop and print “Exiting loop.” to the console.


Leave a Reply

Your email address will not be published. Required fields are marked *