For Loop in Java With Example

1. Introduction

There are several looping statements available in Java, one of which is the for loop. The for loop in Java is used to execute a set of statements repeatedly until a specified condition evaluates to false.

It provides a compact way to initialize a loop variable, check a condition, and update the loop variable. It’s especially useful when we know in advance how many times we want to repeat the execution.

2. The Structure of a For Loop

  • Initialization: This is executed once at the beginning of the loop. It often involves declaring and initializing a loop control variable.
  • Condition: Before each iteration, the loop checks this condition. If the condition evaluates to true, the loop continues; if it evaluates to false, the loop ends.
  • Step: This statement is executed after each iteration. It typically involves incrementing or decrementing the loop control variable.

The Initialization, condition and step used in for statements are optional.

3. Basic For Loop Example

To illustrate, let’s write a Java program that uses a for loop to print numbers from 1 to 5:

In this example, int i = 1 is the initialization where we start counting from 1. The condition i <= 5 ensures that the loop continues as long as i is less than or equal to 5. The step i++ increments i by 1 after each iteration.

If you are still confused by the above concept, let’s understand it with the help of a flow diagram:

For Loop Flow Diagram in Java

Let’s try to print only even numbers now:

Output:

4. Advanced For Loop Concepts

Java for loops are versatile and can be used in various forms to suit different scenarios:

4.1 Labeled For Loops

Java provides a feature called labeled loops, which is particularly useful in nested loop scenarios where you might need to break out of an outer loop from within an inner loop.

A label is an identifier followed by a colon (:) placed before a loop statement, which can then be referenced in break or continue statements to control the flow more precisely.

Here’s an example of using a labeled for loop:

In this example, the outerLoop label is associated with the outer for loop. When the condition i * j > 6 is met within the inner loop, the break outerLoop statement terminates the outer loop, not just the inner one. This feature adds a level of control that allows you to exit multiple loops at once, making it especially handy in complex looping scenarios where simply breaking out of the current loop isn’t sufficient.

4.2 Using Two Variables in For Loop

For loops can use multiple variables, useful for simultaneous iterations or complex conditions.

Let’s say you want to check if a string is a palindrome or not. You can use two variables in the for loop as follows:

In the provided program, two variables, i and j, are used in the for loop to check if the input string is a palindrome. Variable i starts from the beginning of the string (0 index), and j starts from the end (str.length() - 1), moving towards each other to compare characters at mirrored positions until the middle of the string is reached or a mismatch is found.

4.3 Infinite For Loop

An infinite for loop runs endlessly. It’s useful in scenarios where a task needs to repeat indefinitely until externally stopped, such as in server processes or listening for events.

You need to be careful with the condition you provide in the for loop; otherwise, you may end up creating an infinite loop.

For example, let’s say you want to print numbers from 10 to 1 and you use the code below:

In the code above, if you use i++ instead of i–, the loop will enter an infinite loop.

4.4 Enhanced For Loop

Introduced in Java 5, also known as the “for-each” loop, it is ideal for iterating over arrays or collections. It eliminates the need for a counter or iterator variable, making the code cleaner and less prone to errors. This loop is elegant for reading each element in a collection without explicit indexing.

The syntax of the enhance for loop is as follows:

  • Type: The data type of the elements in the array or collection.
  • var: The variable that represents the current element in the loop.
  • arrayOrCollection: The array or collection being iterated over.

Let’s say we have an array of integers and we want to print each element:

This for-each loop reads as “for each int number in numbers, print number“.

This loop iterates over each element in the numbers array, assigning each element in turn to the variable number and then executing the loop’s body.

Given a List<String> listOfStrings object – We can iterate it as follows:

5. Exercise

Let’s apply our knowledge of for loops by writing a program.

Given an array of integers like {32, 45, 53, 65, 43, 23}, your task is to search for a specific element within this array. If the element exists, your program should output ‘PRESENT’; if it doesn’t, it should output ‘NOT PRESENT’.

I would recommend that you try it yourself first and then look at the code below:

Program:

Output:

6. Conclusion

The for loop in Java is a powerful control flow statement that enables concise and readable iteration over a block of code. Whether you’re counting numbers, iterating over arrays, or traversing collections, understanding and using for loops effectively can make your Java programs more efficient and expressive.

 

Was this post helpful?

Leave a Reply

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