Chapter 3 - Java for Beginners Course

For Statement

The for statement is another looping statement that provides us a way to iterate over a numerical range, for example, iterating from 0 to n.

General for loop

The for statement has the following syntax:

for( initialization; termination; increment) {
	// execute this block of code
}

The for loop specifies 3 expressions, all of them optional, that are separated with semi-colons as seen in the syntax snippet above.

Expression Description When is it executed?

Initialization

Used to perform initialization steps for the loop. This is usually to provide an initial value to a variable

It’s executed only once, at the beginning of the for loop

Termination

This is a boolean expression and is the equivalent of the loop condition in a while loop. The loop will continue as long as the termination or loop condition is true. The loop terminates if this condition is false

Once every iteration, at the beginning of the iteration

Increment

Used to update a variable or set of variables after each iteration

Once every iteration, at the end of the iteration

Although the increment expression suggests that it can only be used to increment values, you can also use it to decrement values, for example, if you are iterating from n to 0, instead of from 0 to n.
You can declare a variable in the initialization expression, for example, int i = 0. If you declare a variable, it can only be used in the block of code of the for loop.

As an example, we’ll implement the sum example we used in the while statement section, but this time using a for loop:

int n = 3;
int sum = 0;
for (int i = 1; i <= n; i++) {
    sum = sum + i;
}

System.out.println("The sum from 1 to " + n + " is: " + sum);

Output:

The sum from 1 to 3 is: 6
In simple for loops and in example code that relies on for loops, it is common to use variables named i, j and k as in the example above.
There is a second form of the for loop that we’ll cover in chapter 7 after we introduce arrays and Collections. It is called the enhanced for loop, or the for each loop.

Analysing the for loop example

If we break down our for loop statement, the three expressions in our example are:

  1. Initialization: int i = 1, we are both declaring and initializing variable i. As we are defining the variable here, it can only be used inside the block of code of the for loop.

  2. Termination: i <= n, our loop condition is checking if our loop variable i has already gone past the value of variable n. In our case, the value of n isn’t changing, so this is checking if i is lower than or equal to 3 before starting each iteration.

  3. Increment: i++, after each iteration, we are incrementing our i variable by 1.

In this case, it is easy to see that the loop will iterate 3 times, and on each iteration the value of i is incrementing by 1. i takes the values of 1, 2 and 3 on each iteration, and that value is added to sum, and as a result, sum will be equal to 1 + 2 + 3, which is what we want.

At the end of the 3rd iteration, the value of i is incremented again, taking a value of 4, however, this causes the loop condition to be false (4 isn’t less than or equal to 3), causing the loop to finish.

The execution then continues at the next line after the block of code of the for loop, in our case, the line that prints out the message The sum from 1 to 3 is: 6.

Try running the application with different values of n and with different loop expressions. For example, what happens if you do i+=2 in the increment statement? or what if n is a negative value?

Optional expressions

As mentioned above, all of the 3 expressions in the for loop are optional and you can omit them if not required (the semi-colons are mandatory though!). In the case where all 3 expressions are omitted, the result is a for loop that looks like this:

for( ; ; ) {
	// do something
}

This for loop is valid and represents an infinite loop.

This is an equivalent version of a while loop using true as the boolean expression, as in: while(true) { //…​ }. This is also an infinite loop.
Code in GitHub

Get the code for this tutorial using the links below.

Project Repo
Download code for this step
Main class for this step
Dependencies

This is a list of recommended tutorials or courses that might be useful before starting this one.

Contents
Welcome to the Course!
Course Introduction
Chapter 1 - Building Blocks
Quick introduction to Java Variables Classes And Objects Class Example - Defining a class Object Examples - Creating instances Java Application Example - Running our first app Accessing class members - The dot operator Packages - Organizing the code
Chapter 2 - Primitives and Operators
Primitives Arithmetic Operators Assignment Operator Unary Operators Equality and Relational Operators Conditional Operators
Chapter 3 - Statements and Control Flow
Expressions Statements If-Then Statement If-Then-Else Statement More If Statements Switch Statement While and Do-While Statements For Statement Branching Statements Exception Handling
Chapter 4 - Code Example
Example Project - A Simple Vending Machine Adding money Delivering Items Giving Change
Chapter 5 - Classes and Interfaces
Introduction Access Level Modifiers Class Declaration - Class, Methods and Fields Class Declaration - Constructors Inheritance Basics Inheritance - Constructors Inheritance - Methods and Fields Polymorphism Abstract Classes and Methods Interfaces Static Class Members Class Composition Final Classes and Class Members Generic Classes
Chapter 6 - Base Object Behaviors
Introduction Type Comparison Type Casting Object Equality - The Contract Object Equality - Common Pitfalls Object String Representation Garbage Collection Object Comparison Primitive Wrappers and Autoboxing
Chapter 7 - Data Structures
Introduction Arrays - Declaration and Creation Arrays - Basic Operations Core Collection Interfaces List and ArrayList - Basic Operations ArrayList Internals Introduction to Hash Tables Map and HashMap - Basic Operations Set and HashSet - Basic Operations
Chapter 8 - Anonymous classes and lambdas
Introduction Filtering a List Anonymous Classes Lambdas Built-in Functional Interfaces
Chapter 9 - Streams
Introduction Creating Streams Intermediate Operations Terminal Operations