Lesson Overview

Welcome to our lesson on Java's for loop. We use loops to repeat some action multiple times without the need to write the code for every iteration. A for loop can be likened to a set task — say, visiting each planet in our solar system one by one. By the end of this journey, you will understand and be able to use the basic for loop and the enhanced for loop in Java.

Understanding the Basic For Loop in Java

Imagine lining up your favorite planet toys in order. You take one, put it in line, and repeat until you run out of toys. This is precisely how the basic for loop works in Java!

Here's the syntax:

This loop does the following:

  • First, we do the initialization
  • Then, while the condition is true, we keep executing the task inside the loop body
  • After each iteration, we execute post-iteration actions that change the state in some way

Now, let's demonstrate this with code that prints numbers 1 through 5:

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal