For Loop Program in Java: Syntax and Examples

Updated on 01/09/20256,533 Views

Introduction

Ever needed to repeat a task 10, 100, or even 1,000 times in your code? That's where the for loop comes in, it's your personal automation tool for any repetitive job.

This tutorial is your complete guide to writing a For Loop Program in Java. We'll break down its simple three-part structure, show you how to loop through arrays and collections, and even explore the curious (and sometimes dangerous) case of the infinite for loop in Java.

By the end, you'll have the confidence to use this essential tool to write cleaner and more powerful code. Let's get looping!

Looking to advance your Java framework skills? Check out upGrad’s Online Software Engineering Courses. Start today to strengthen your foundation and accelerate your career growth by learning JavaScript, Node.js, APIs, React, and more!

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.

Accelerate your tech career by mastering future-ready skills in Cloud, DevOps, AI, and Full Stack Development. Gain hands-on experience, learn from industry leaders, and develop the expertise that top employers demand.

  • Professional Certificate Program in Cloud Computing and DevOps
  • AI-Powered Full Stack Development Course by IIITB
  • Future-Proof Your Tech Career with AI-Driven Full-Stack Development

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.

Also Read: JDK in Java: Comprehensive Guide to JDK, JRE, and JVM

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.

Also Read: Control Statements in Java: Types, Flowcharts, and Code Examples

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.

Also Read: 50 Java Projects With Source Code in 2025: From Beginner to Advanced

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.

Also Read: File Handling in Java: How to Work with Java Files?

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.

Also Read: Java Language History: Why Java Is So Popular and Widely Used Today

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.

Also Read: Top 10 Java Frameworks Powering Modern Application Development

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

In short, you now know how to write a For Loop Program in Java, from its basic structure to the cautionary infinite for loop in java. This is a core skill for handling any repetitive task, especially with arrays and collections, allowing you to write much cleaner and more efficient code.

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.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow

FREE COURSES

Start Learning For Free

image
Pavan Vadapalli

Author|911 articles published

Pavan Vadapalli is the Director of Engineering , bringing over 18 years of experience in software engineering, technology leadership, and startup innovation. Holding a B.Tech and an MBA from the India....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

Top Resources

Recommended Programs

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 10 AM to 7 PM

text

Indian Nationals

text

Foreign Nationals