Donate HTML/CSS JavaFX Java Home
Array Data Structures Array List Data Structures Linked List Data Structures Stack Data Structures Queue Data Structures While Loops Do-While Loops For Loops For-each Loops If, Else, and Multi-Way If Statements Switch Statements Try-Catch Blocks Comment Types and Javadoc Java Classes Java Methods

For Loops

Code Description:

A For loop is a unique loop type defined with a very concise syntax. Within the parenthesis, we create a counter variable, the condition, and the action to perform after an iteration is executed. In the example below, we create a new counter integer variable which is named "i" (by convention) and set it to 0. Our condition is checking if "i" is less than ( < ) 5. After the loop executes we increment "i" by 1 ( i++ ). The three components are separated by semicolons in between. For loops should be used whenever you know exactly how many times a loop needs to execute.

For Loop Syntax:

for (int i = 0; i < 5; i++) {

Runnable For Loop Example Code:

public class Demo {

    public static void main(String[] args) {

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


How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.


For Loop Output Image

Important Notes:

  • The "break" keyword can be used in a loop to fully terminate its execution at any point.
  • The "continue" keyword ends the current iteration of a loop immediately and moves onto the next iteration.
  • Be careful and make sure that the counter will eventually no longer satisfy the condition. Otherwise, you will have an infinite loop.

Related Links:

While Loops Do While Loops For-each Loops