Java For Loop Syntax & Examples

Java For Loop Syntax & Examples: In this article, we will learn about loops in Java programming language. One of the core features of Java is the for loop, which allows developers to iterate over a collection of data or perform a set of actions repeatedly for a fixed number of times. The for loop is essential for developers to create efficient and concise code to handle complex problems.

In this article, we will explore the basics of Java for loop, including its syntax, structure, and various use cases. We will also examine some advanced techniques that can be used to optimize the performance of loops and avoid common pitfalls. Whether you are a beginner or an experienced developer, mastering the for loop is a crucial step toward becoming a proficient Java programmer.

We mainly have three loops in Java: For Loop, While Loop, and do-while loop. But in this article, we will learn about the for loops in Java and the other loop we have discussed in a separate post, and you can follow these links to learn the While Loop in Java and the Do-while loop in Java.

Java For Loops

The for loop is a control flow statement that allows developers to execute instructions repeatedly based on a specified condition. The for-loop syntax in Java is straightforward and consists of three parts: initialization, condition, and increment/decrement. The initialization part is where we declare and initialize the loop counter variable. In the condition part, we specify the condition that must be met for the loop to continue executing. The increment/decrement part is where we update the value of the loop counter variable after each iteration.

Java For Loop Syntax

for (initialization; condition; increment / decrement) 
{
    // Loop body statements
}

The Flow of Execution of the For Loop

  • In this loop type, the initialization happens only once, meaning the initialization part executes only once.
  • The condition is evaluated for each iteration. If the condition is true, then the execution will enter into the loop body area and execute the statements, and if the condition fails, then the execution flow comes out of the loops. The statements that are present outside of the loop body will execute.
  • In each loop execution, the loop body and the increment/decrement part of the loop will execute. And the behavior increment or decrement of the values as mentioned in the syntax.
  • After increment/decrement execution, the execution jumps to the condition. It re-evaluates if the condition is true, then the loop body statements will be executed. If the condition fails, then the execution comes out from the loop body statements.

Java For Loop Example

The for loop is commonly used to iterate over arrays, lists, and other data collections. Using a for loop, we can access each collection element and perform operations on them. For example, we could use a for loop to calculate the sum of all the elements in an array or find the maximum value in a list.

Another use case for the for loop is to execute a set of instructions a fixed number of times. This is useful when we must repeat a set of actions a specific number of times. For example, we could use a for loop to print a sequence of numbers or generate a pattern of characters.

Program: Write a Java Program to Print 1 to 10
package java_Basics;
public class ForLoop_Example 
{
   public static void main(String[] args) 
   {
      for (int i = 1; i <= 10; ++i) 
      {
         System.out.println("Value Of I Is:- " + i);
      }
   }
}

Output:

Value Of I Is:- 1
Value Of I Is:- 2
Value Of I Is:- 3
Value Of I Is:- 4
Value Of I Is:- 5
Value Of I Is:- 6
Value Of I Is:- 7
Value Of I Is:- 8
Value Of I Is:- 9
Value Of I Is:- 10

One of the advantages of the for loop is that it allows us to write concise and readable code. We can avoid cluttering our code with unnecessary details by encapsulating the loop logic within a single statement. Furthermore, the for loop is highly customizable, allowing us to fine-tune its behavior to suit our specific needs.

Nested For Loop In Java

A nested for loop is a loop within a loop. This means we have a loop containing another loop inside its block. Nested For loops are useful when we need to iterate over multiple arrays or collections of data simultaneously. In a nested for loop, the outer loop is responsible for iterating over the rows, while the inner loop iterates over the columns.

Here’s an example of a nested for loop that prints a multiplication table:

Program: Print a Multiplication Table
package com.softwaretestingo.ConditionalStatements;
public class NestedForLoopEx 
{
	public static void main(String[] args) 
	{
		for (int i = 1; i <= 10; i++) 
		{
			for (int j = 1; j <= 10; j++) 
			{
				System.out.print(i * j + " ");
			}
			System.out.println();
		}
	}
}

In this example, we have two For loops, one inside the other. The outer loop iterates over the rows from 1 to 10, while the inner loop iterates over the columns from 1 to 10. For each row and column combination, we calculate the product of the two numbers (i * j) and print it to the console, followed by a space. After each row, we print a newline character to move to the next line.

The output of this code will be a multiplication table that shows the product of all numbers from 1 to 10:

1 2 3 4 5 6 7 8 9 10 
2 4 6 8 10 12 14 16 18 20 
3 6 9 12 15 18 21 24 27 30 
4 8 12 16 20 24 28 32 36 40 
5 10 15 20 25 30 35 40 45 50 
6 12 18 24 30 36 42 48 54 60 
7 14 21 28 35 42 49 56 63 70 
8 16 24 32 40 48 56 64 72 80 
9 18 27 36 45 54 63 72 81 90 
10 20 30 40 50 60 70 80 90 100 

As we can see, the nested for loop allows us to iterate over all possible combinations of rows and columns and perform a specific action on each combination. This is just one example of how nested For loops can be used in Java programming.

Many other use cases exist where nested for loops can be applied, depending on the program’s specific requirements. If you are looking for more examples of Nested For Loops, you can check the Number Pattern Programs or Star Pattern Programs examples.

Infinite For Loop

The loop will run forever if the test condition is never false. This type of loop is called an infinite loop. Here is an example of an Infinite loop:

Program: Infinite Loop In Java
package java_Basics;
public class InfiniteForLoop_Example 
{
   public static void main(String[] args) 
   {
      for (int i = 1; i <= 10; --i) 
      {
         System.out.println("Hello");
      }
   }
}

Java For Each Loop (Enhanced for Loop)

A Java foreach loop is a simplified version of the for loop designed to iterate over data collections such as arrays or lists. The for each loop is also known as the enhanced for loop, as it provides a simpler and more concise way of iterating over data compared to traditional For loops.

Here’s an example of a for-each loop that iterates over an array of integers and prints each element to the console:

Syntax For Java Foreach Loop

for(data_type variable : array_name)
{    
//code to be executed    
} 

How does Each loop work

The for-each loop works in the following way:

  • It iterates each item in the given collection or array.
  • Stores each item in a variable (item)
  • Executes the body for each loop.

Here’s an example of a for-each loop that iterates over an array of integers and prints each element to the console:

Program: For Each Loop With Integer Array
package com.softwaretestingo.conditionalstatements;
public class ForEachEx1 
{
	public static void main(String[] args) 
	{
		int[] numbers = {1, 2, 3, 4, 5};
		for (int number : numbers) 
		{
			System.out.println(number);
		}
	}
}

This example has an array of integers called “numbers”. We want to print each element of the array to the console. We use a for-each loop instead of a traditional for loop, simplifying iterating over arrays. The loop automatically iterates over each array element and assigns it to a variable called “number”. The loop continues until all elements of the array have been processed.

The output of this code will be:

1
2
3
4
5

As we can see, the for-each loop allows us to iterate over an array of data and perform a specific action on each element more concisely and readably.

Here’s another example of a for-each loop that iterates over a list of strings and prints each element to the console:

Program: For Each Loop With String Array
package com.softwaretestingo.ConditionalStatements;
import java.util.ArrayList;
import java.util.List;
public class ForEachEx2 
{
	public static void main(String[] args) 
	{
		List<String> fruits = new ArrayList();
		fruits.add("Apple");
		fruits.add("Banana");
		fruits.add("Orange");

		for (String fruit : fruits) 
		{
		    System.out.println(fruit);
		}
	}
}

In this example, we have a list of fruits called “fruits”. We want to print each element of the list to the console. Once again, we use a for-each loop to simplify the process of iterating over the list. The loop automatically iterates over each list element and assigns it to a variable called “fruit”. The loop continues until all elements of the list have been processed.

The output of this code will be:

Apple
Banana
Orange

As we can see, the for-each loop allows us to iterate over a data collection and perform a specific action on each element more concisely and readably.

One important thing to note about each loop is that they are only applicable for iterating over data collections. If we need to iterate over a range of values or perform a specific action a specific number of times, we will still need to use traditional For loops.

For Each Loop In Java Example 1: [With For Loop]

Suppose we want to print all the elements of a character array; then, we can print the elements in 2 ways: using for loop OR Foreach loop.

package java_Basics;
public class ForLoopExample_ForEach 
{
   public static void main(String[] args) 
   {
      char[] vowels = {'a', 'e', 'i', 'o', 'u'};
      for (int i = 0; i < vowels.length; ++ i) 
      {
         System.out.println(vowels[i]);
      }
   }
}

We can also print the same elements using For Each loop like below:

package java_Basics;
public class ForEachLoop_Example 
{
   public static void main(String args[])
   {
      char[] vowels = {'a', 'e', 'i', 'o', 'u'};
      // foreach loop
      for (char item: vowels) 
      {
         System.out.println(item);
      }
   }
}

Key Points of For each loop

  • It starts with the keyword for like we are using in for loop.
  • Instead of initialization, condition, and increment/decrement, here we need to declare the data type of an array or collection, followed by the array or collection name.
  • You can use the item or loop variable instead of the index array element in the loop body.
  • Each loop is preferred when you are working with arrays or collections.

Limitations of the for-each loop

  • For each loop is inappropriate when you want to modify the array.
  • For each loop, iterate elements individually so we never get the element’s index.
  • We cannot iterate elements from a specific position using the for-each loop.
  • We cannot process two decision-making statements at once using the for-each loop.

Conclusion:

The for-each loop is a simplified version of the for loop that provides a more concise and readable way of iterating over collections of data, such as arrays or lists. Using for-each loops, we can write easier code to understand and maintain, which can be especially helpful in larger and more complex programs.

Finally, We believe that conversation is the best way to learn. If you have any additional insights or perspectives on the topic we discussed in our post, please share them in the comments section below.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment