top

Search

Java Tutorial

.

UpGrad

Java Tutorial

For Loop in Java

Introduction

Dive into the world of Java. Today's focus: the pivotal 'For Loop'. It's a cornerstone in coding, fundamental for iteration in Java.

Overview

In this tutorial, we will delve into the 'For Loop' structure, its applications, and nuances. You'll grasp why it's a key tool in a Java programmer's arsenal and gain practical knowledge to tackle real-world coding tasks with confidence.

Parts of Java For Loop

Here are the details for the three parts of a 'For Loop' in Java: 

1. Initialization Expression

This starts the loop. It initializes the loop variable. Usually, we use it to set a counter to a specific value. It executes only once.

2. Test Expression

This checks a condition. If it returns true, the loop continues. If it returns false, the loop ends. We usually check if the counter has reached a certain value.

3. Update Expression

This updates the loop variable. After each loop iteration, this expression runs. We often use it to increment or decrement the counter.

The Difference Between For Loop - While Loop - Do-While Loop

Loop Type

Initialization

Test Before Iteration

Runs at Least Once

Update Statement

For Loop

Yes

Yes

No

Yes

While Loop

No

Yes

No

No

Do-While Loop

No

No

Yes

No

For Loop initializes a counter, tests before iteration, and contains an update statement within the loop structure itself.

While Loop in Java checks the condition before entering the loop but does not have an inherent initialization or update statement.

Do-While Loop ensures the code block executes at least once, as it checks the condition after running the loop. But similar to While Loop, it lacks inherent initialization and update statements.

For Loop in Java

The 'For Loop' structure in Java is as follows:

For loop in Java example:

Here's a simple example of a 'For Loop' that prints numbers from 1 to 5:

In this case, int i=1 is the initialization part, where we initialize our counter i to 1.

i<=5 is the test expression. Before each loop iteration, we check if this condition is true. If i is less than or equal to 5, we continue the loop. If not, we stop the loop.

i++ is the updated expression. After each iteration of the loop, we increase i by one.

Running this code, you'll see the numbers 1 through 5 printed on your console.

For Loop In Java Syntax

Here's what each part does:

  1. Initialization: This statement executes only once, setting the loop variable to an initial value.

  2. Condition: This is a boolean expression that the program evaluates before each loop iteration. If it's true, the loop continues; if it's false, the loop stops.

  3. Increment/Decrement: This statement updates the loop variable after each iteration.

  4. Code to be executed: This is the code block that the loop executes for each iteration.

Types of For Loops in Java

Java offers many types of 'For Loops' for diverse scenarios. They are:

1. Simple For Loop

The basic form of 'For Loop' we discussed earlier is the Simple For Loop. It consists of initialization, testing, and update expressions.

Example:

2. Enhanced For Loop (For Each Loop)

The Enhanced For Loop, also known as the "for-each" loop, is designed for iteration over arrays or collections, making the code more readable.

Example:

3. Labeled For Loop

A Labeled For Loop allows us to name our loops. This can be beneficial when we have nested loops and  want to break or continue a specific outer loop.

Example:

4. Infinite For Loop

An Infinite For Loop continues indefinitely. This happens if the test condition never becomes false. It's usually a coding error, but can sometimes be useful.

Example:

These variations offer flexibility to handle different scenarios in programming with Java.

How Does a For Loop Work?

  1. The loop begins with the initialization statement (only executed once). Here, you typically declare and set your loop variable.

  2. Next, it checks the test condition. If the condition is true, the loop continues; if it's false, the loop ends.

  3. The code block inside the loop executes.

  4. After executing the code block, the loop hits the update statement. This usually increments or decrements your loop variable.

  5. The loop returns to step 2, checking the condition again. It continues this process until the test condition is false.

Remember, 'For Loops' are excellent for cases where you know how many times the loop should run.

Flow Chart For “for loop in Java”

Explanation:

  1. Start Node: The flowchart starts at the Start node.

  2. Initialization Node: Next, there is an operation node for the initialization step. This is where you typically initialize your loop variable.

  3. Decision Node (Test Condition): This node checks the loop's test condition. If it's true, the process moves to the next node. If it's false, it leaps to the End node.

  4. Operation Node (Code Execution): This represents the execution of the code block within the loop.

  5. Operation Node (Update Statement): After the code execution, the process moves to the update step where the loop variable gets updated.

  6. Back to Decision Node: Post the update, the control goes back to the decision node (test condition). This cycle continues until the test condition is false.

  7. End Node: When the test condition becomes false, the loop ends and the flow of control moves to the End node.

This is a typical flowchart for a 'For Loop' in Java. It illustrates the cyclic and iterative nature of the loop, helping understand the flow of the loop process.

Java For-Each Loop

The For-Each Loop, also known as the Enhanced For Loop, offers a simpler way to iterate over arrays or collections. It's ideal for scenarios where you don't need to manipulate the elements' indexes.

Here's its general structure:

Type represents the data type of the elements. var is the variable that takes the value of each element during the iteration. array is the array or collection you're traversing.

Example

Consider the following array of integers:

Here, number takes on the value of each element in the numbers array. The loop prints out these values one by one. So, the output would be 1, 2, 3, 4, and 5, each on a new line.

Output

Note

While the For-Each Loop is simple and easy to use, it doesn't provide control over the index. You can't know the index of the current element within the loop, nor can you alter the iteration step (like skipping every other element). If you need such control, use a traditional For Loop.

Example with Collections

The For-Each Loop also works great with collections. Here's an example with an ArrayList:

Output

In this example, name takes the value of each element in the names ArrayList. The loop prints out these names one by one. So, the output would be Alice, Bob, Charlie, each on a new line.

Java Infinite for Loop

An Infinite For Loop is a loop that runs indefinitely. This usually occurs when the condition in the loop never becomes false. It's often due to a programming error, but sometimes, it's intentional.

Here's the structure of an Infinite For Loop:

Example

Here's an example of an infinite loop that would print "Hello, World!" endlessly:

Note

Running an infinite loop like the one above will print "Hello, World!" continuously until you manually stop the program.

In practical scenarios, infinite loops are not usually desirable as they can cause the program to become unresponsive or consume too much CPU time. Yet, they can be useful in cases where a program needs to run indefinitely until it's manually stopped, such as a server waiting for client requests.

Important

Please be careful when running infinite loops, as they can make your program run indefinitely, consuming system resources. Always ensure there's a valid way to stop the loop.

Nested For Loop in Java

A Nested For Loop in Java means there is a For Loop inside another For Loop. It's very useful when dealing with multi-dimensional data structures like arrays.

Here's the structure:

Example

An example of a nested for loop that prints a 5x5 matrix:

Output

The output would be:

This forms a 5x5 matrix, where each row is the numbers 1 through 5.

Nested For Loops are very useful in Java for manipulating multi-dimensional data structures or performing repeated operations.

Conclusion

The 'For Loop' in Java is a versatile control structure, integral to iterative operations in your code. Whether it's the traditional 'For Loop', the 'Enhanced For-Each Loop', the 'Labeled For Loop', or even the 'Infinite For Loop', each variant presents unique utilities in different programming contexts. Coupled with the power of nested loops, these tools provide a robust approach to handling repetitive tasks efficiently. Mastery of 'For Loops' empowers you to deal effectively with arrays, collections, and multi-dimensional data structures, enhancing your Java programming proficiency.

FAQs

1. What happens if I leave out a part of the 'For Loop' syntax in Java?

Leaving out a part of the 'For Loop' syntax can have different effects. For instance, if you omit the initialization part, you must ensure the loop variable is initialized elsewhere in the code. If the condition is absent, the loop becomes an infinite loop. 

2. Can I use data types other than int for the loop variable in a 'For Loop'?

Absolutely! You can use other data types such as byte, short, long, or even char for the loop variable. However, the choice should make sense according to your looping requirements. For example, using a double or float is generally unusual, unless you need to increment by fractions.

3. How does 'For Loop' behave with an empty body?

A 'For Loop' with an empty body will still execute the initialization, condition check, and increment/decrement operations. However, since the body is empty, no substantial work gets done inside the loop. In most scenarios, having an empty loop body would not be useful.

4. Are there alternatives to 'For Loops' in Java for iterative operations?

Java provides many alternatives for iterative operations, such as 'While Loop' and 'Do-While Loop'. These control structures can be used interchangeably, depending on the specific use-case. Moreover, Java provides a stream API and methods like forEach for collections, offering a functional programming approach to iterations.

Leave a Reply

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