Java for Loop Tutorial with Examples
Introduction
Computers are good at repeating work, and loops are how a program repeats a block of code. The for loop is the loop to use when you know how many times something should repeat - count from 1 to 10, go through each position of an array, or run a calculation for each year of a loan. This tutorial explains the Java for loop with examples. We will start with its syntax, and trace exactly how it runs. We will then count up, down and in steps, and use a loop to calculate totals. Next we will nest loops to print patterns and tables. Lastly, we will look at the variations of the loop header, and the most common for loop mistakes.
(Note - Loops use the comparison and increment operators from Arithmetic, Relational and Logical OperatorsClick to read tutorial: Java Arithmetic, Relational and Logical Operators and Increment/Decrement OperatorsClick to read tutorial: Java Assignment, Increment/Decrement and Ternary Operators.) Syntax of the for loop
Where,
OUTPUT of the above code
How the loop runs, step by step
Counting up, down and in steps
The update can change the counter in any way - count down with
OUTPUT of the above code
Calculating with a loop
A loop often builds up a result - a sum, a product or a count - in a variable declared before the loop, so that it still exists afterwards. Here, a loop calculates a factorial, and another one shows how savings grow with interest, year by year.
OUTPUT of the above code
Explanation of the code
Nested for loops
A loop can contain another loop. The inner loop runs completely for each iteration of the outer loop. Nested loops are used for rows and columns - tables, grids, two-dimensional arrays and patterns.
OUTPUT of the above code
In the multiplication table, the outer loop chooses the row and the inner loop prints each column of that row, so the inner body runs 4 × 4 = 16 times in total. In the triangle, the number of stars depends on the row number.
Variations of the loop header
OUTPUT of the above code
Common for loop mistakes
(Note - Loops use the comparison and increment operators from Arithmetic, Relational and Logical OperatorsClick to read tutorial: Java Arithmetic, Relational and Logical Operators and Increment/Decrement OperatorsClick to read tutorial: Java Assignment, Increment/Decrement and Ternary Operators.) Syntax of the for loop
for (initialization; condition; update) { body }initializationruns once, before the loop starts. It usually declares a loop counter, such asint i = 1.conditionis checked before every repetition (iteration). If it istrue, the body runs; if it isfalse, the loop ends.updateruns after every iteration, usually moving the counter on, such asi++.bodyis the block of code to repeat.
A simple for loop
//CountToFive.java
public class CountToFive {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
System.out.println("Loop finished");
}
}
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 Loop finished
int i = 1runs once.i <= 5is checked:1 <= 5istrue, so the body printsIteration 1.i++makesi2, and the condition is checked again - and so on.- After the fifth iteration,
i++makesi6.6 <= 5isfalse, so the loop ends and the program continues withLoop finished.
i is declared in the loop header, so it exists only inside the loop. If the condition is false from the start, the body never runs at all.
i--, or step by more than one with i += 2.
Counting down and in steps
//CountingLoops.java
public class CountingLoops {
public static void main(String[] args) {
System.out.print("Countdown: ");
for (int i = 5; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println("Lift off!");
System.out.print("Even numbers: ");
for (int i = 0; i <= 10; i += 2) {
System.out.print(i + " ");
}
System.out.println();
System.out.print("Powers of 2: ");
for (int p = 1; p <= 1000; p *= 2) {
System.out.print(p + " ");
}
System.out.println();
System.out.print("Letters: ");
for (char c = 'a'; c <= 'e'; c++) {
System.out.print(c);
}
System.out.println();
}
}
Countdown: 5 4 3 2 1 Lift off! Even numbers: 0 2 4 6 8 10 Powers of 2: 1 2 4 8 16 32 64 128 256 512 Letters: abcde
Totals and running calculations with for loops
//LoopCalculations.java
public class LoopCalculations {
public static void main(String[] args) {
int n = 10;
long factorial = 1;
for (int i = 2; i <= n; i++) {
factorial *= i;
}
System.out.println(n + "! = " + factorial);
double balance = 1000.0;
double rate = 0.05;
for (int year = 1; year <= 5; year++) {
balance += balance * rate;
System.out.printf("Year %d: %.2f%n", year, balance);
}
int[] scores = {72, 85, 90, 64, 88};
int total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
System.out.println("Average score: " + (double) total / scores.length);
}
}
10! = 3628800 Year 1: 1050.00 Year 2: 1102.50 Year 3: 1157.63 Year 4: 1215.51 Year 5: 1276.28 Average score: 79.8
factorialis along, because factorials grow very fast - 13! is already too large for anint.- The loop over the array uses the classic pattern
for (int i = 0; i < scores.length; i++). Array positions run from 0 tolength - 1, so the condition uses<, not<=. When you only need the values, not their positions, the enhanced for loopClick to read tutorial: Java Enhanced for Loop (for-each) with Examples is simpler.
Nested for loops - a table and a pattern
//NestedLoops.java
public class NestedLoops {
public static void main(String[] args) {
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= 4; col++) {
System.out.printf("%4d", row * col);
}
System.out.println();
}
System.out.println();
int height = 4;
for (int row = 1; row <= height; row++) {
System.out.print(" ".repeat(height - row));
for (int star = 1; star <= 2 * row - 1; star++) {
System.out.print("*");
}
System.out.println();
}
}
}
1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16 * *** ***** *******
- Several variables: the initialization and update can contain several parts, separated by commas -
for (int i = 0, j = 10; i < j; i++, j--)moves two counters towards each other. - Optional parts: any of the three parts can be left out.
for (; i < 10; )works like awhileloop. - Infinite loop:
for (;;)has no condition, so it repeats forever, until abreakorreturninside the body ends it. See break and continueClick to read tutorial: Java break, continue and Labeled Loops Explained.
A for loop with two counters
//TwoCounters.java
public class TwoCounters {
public static void main(String[] args) {
String word = "level";
boolean palindrome = true;
for (int i = 0, j = word.length() - 1; i < j; i++, j--) {
if (word.charAt(i) != word.charAt(j)) {
palindrome = false;
}
}
System.out.println(word + " is a palindrome: " + palindrome);
}
}
level is a palindrome: true
- Off-by-one errors: running one time too many or too few.
i <= array.lengthgoes one position past the end of an array and throws anArrayIndexOutOfBoundsException. Check where the counter starts and whether the condition should use<or<=. - A semicolon after the header:
for (int i = 0; i < 5; i++);has an empty body. The loop runs five times doing nothing, and the block after it runs once. - An update that never reaches the end:
for (int i = 0; i < 10; i--)moves away from the end and loops (practically) forever. - Changing the counter inside the body: it makes the loop hard to follow. Let the update part be the only place the counter changes.
Java Fundamentals Tutorials
Java Switch Expressions: Arrow Labels and yieldClick to read tutorial: Java Switch Expressions: Arrow Labels and yield Java while and do-while Loops with ExamplesClick to read tutorial: Java while and do-while Loops with Examples Java if, else if and else Statements with ExamplesClick to read tutorial: Java if, else if and else Statements with Examples Java switch Statement Tutorial with ExamplesClick to read tutorial: Java switch Statement Tutorial with Examples Java Enhanced for Loop (for-each) with ExamplesClick to read tutorial: Java Enhanced for Loop (for-each) with Examples Java break, continue and Labeled Loops ExplainedClick to read tutorial: Java break, continue and Labeled Loops Explained What is Java? History, Features, Editions and UsesClick to read tutorial: What is Java? History, Features, Editions and Uses
Java Switch Expressions: Arrow Labels and yieldClick to read tutorial: Java Switch Expressions: Arrow Labels and yield Java while and do-while Loops with ExamplesClick to read tutorial: Java while and do-while Loops with Examples Java if, else if and else Statements with ExamplesClick to read tutorial: Java if, else if and else Statements with Examples Java switch Statement Tutorial with ExamplesClick to read tutorial: Java switch Statement Tutorial with Examples Java Enhanced for Loop (for-each) with ExamplesClick to read tutorial: Java Enhanced for Loop (for-each) with Examples Java break, continue and Labeled Loops ExplainedClick to read tutorial: Java break, continue and Labeled Loops Explained What is Java? History, Features, Editions and UsesClick to read tutorial: What is Java? History, Features, Editions and Uses