Konstantina Dimtsa

About Konstantina Dimtsa

Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

Java for loop Example

If you need to execute a block of code many times, then you will definitely have to use a mechanism named as loop.
Java provides three looping mechanisms, which are the following:

  • while Loop
  • do-while Loop
  • for Loop

In this example, we will show how to use the for loop mechanism. Also, we will show the enhanced for loop, which was introduced in Java 5 and it is mainly used for Arrays.

1. Syntax of for loop

The for statement provides a compact way to iterate over a range of values until a particular condition is satisfied. The general form of the for statement is the one following:


for (initialization; condition; update) {
          //statement expressions
}
  • initialization: This expression declares and initializes the loop control variable. It’s executed only once, when the loop begins.
  • condition: If the condition evaluates to true, the statement expressions are executed. If the condition evaluates to false, the loop terminates without the execution of the body of the loop.
  • update: The update expression is invoked after each execution of the body of the loop and updates the loop control variable.

2. Example of for loop

Let’s see an example of the for loop mechanism. Create a java class named ForLoopExample.java with the following code:

ForLoopExample.java

package com.javacodegeeks.javabasics.forloop;

public class ForLoopExample {
	public static void main(String args[]) {

		for (int i = 0; i < 5; i++) {
			System.out.println("i is: " + i);
		}

		System.out.println("Print again the i values, with different condition");

		for (int i = 0; i <= 5; i++) {
			System.out.println("i is: " + i);
		}

		System.out.println("Print the array Cities");
		String[] cities = { "Athens", "Thessaloniki", "Chania", "Patra",
				"Larissa" };

		for (int i = 0; i < cities.length; i++) {
			System.out.println(cities[i]);
		}
	}
}

In the above code, we can see two loop which seems to be the same but they have a basic difference in their conditions. The first loop evaluates to true as long as the i value is strictly less than 5 but the second loop evaluates to true even when the i value is equal to 5. Finally, we have another loop printing an array named “cities”. The condition evaluates to false when the counter i is greater than or equal to the array’s length.
If we run the above code, we will get the following results:

  • Output:
i is: 0
i is: 1
i is: 2
i is: 3
i is: 4
Print again the i values, with different condition
i is: 0
i is: 1
i is: 2
i is: 3
i is: 4
i is: 5
Print the array Cities
Athens
Thessaloniki
Chania
Patra
Larissa

As we see in the output, the first loop does not print the the i value when the i is equal to 5, while the second loop does. It may seem that this is too much detail, but actually, one more or less execution of the loop may be critical for each program.

3. Syntax of the “enhanced” for loop

As we mentioned in the introduction, Java 5 introduced the enhanced for loop as a simpler way to iterate through all the elements of a Collection. This for loop is commonly used by arrays, when you wish to step through the elements of the array in first-to-last order, and you do not need to know the index of the current element. The syntax of this loop is the following:


for (declaration : expression) {
   //Statement expressions
}
  • declaration: A new variable is declared, which is of the same type as the type of the elements of the array. This variable is used in the body of the loop and its value is the same as the current array element. The colon in the syntax can be read as “in.”
  • expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.

4. Example of the “enhanced” for loop

Let’s see an example of the enhanced for loop mechanism. Create a java class named EnhancedForLoopExample.java with the following code:

EnhancedForLoopExample.java

package com.javacodegeeks.javabasics.forloop;

public class EnhancedForLoopExample {

	public static void main(String args[]) {
		String[] cities = { "Athens", "Thessaloniki", "Chania", "Patra",
				"Larissa" };

		for (String cityname : cities) {
			System.out.println(cityname);
		}

	}
}

In the above code, we use the array from the previous example and print it with the enhanced for loop. The declaration expression is a variable cityname which is of type String, just as the type of the elements of the array cities.

  • Output:
Athens
Thessaloniki
Chania
Patra
Larissa

5. Download the source code

This was a for loop example in Java. You can download the source code from here: ForLoopExample.zip

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books