Site icon TestingDocs.com

Java For Loop with Examples

Overview

Java for loop is a repetitive structure and is used to execute a set of statements in repetition. We can use this loop when the number of iterations is fixed or known to the developer beforehand.

For loops in Java can be

 

Simple for loop

for loop is a simple loop construct. We can control the number of iterations with a loop counter variable.

Syntax

The general syntax of the for loop

for(initialization; boolean_condition; update) {

//loop statements

}

The initialization part is used to declare and initialize loop variable/s that will be used by the loop. For example, we can write the initialization as

int i = 0

This declares a loop variable i and initializes it to 0.

The boolean_condition is the condition that will be checked in each loop iteration. The loop condition is evaluated before each iteration. The for loop executes the iteration if the condition is true. If the condition is false the loop will be terminated.

The update part usually contains the loop variable increment/ decrement operation. For example, i++, i–-, etc.

Example

Let’s look at a simple example that illustrates the usage of the for loop. A program to print numbers from 1 to 10.

/*
 * Java For Loop Demo Program
 * Program Description:
 * Print numbers from 1 to 10
 * Java Tutorials - www.TestingDocs.com
 */
public class SimpleForLoopDemo {

	public static void main(String[] args) {
		// Java For Loop
		for (int i = 1; i <= 10; i++) {
			System.out.println(i);
		}
	}
}

 

foreach Loop

foreach loop is used to iterate over a Java collection or an array. This loop does a one-pass of all the elements in the collection.

Syntax

for(datatype variable: collection){

//loop statements

}

Example

In the example, we will declare an array of marks(5 subjects) and compute the total marks using a foreach loop.

public class ForEachDemo {

	public static void main(String[] args) {
		// marks array 5 subjects
		double marks[]= {73.5,66.5,72,90,56};
		double total = 0.0;
		// foreach loop
		for(double mark: marks) {
			total += mark;
		}
		System.out.println("Total Marks="+ total);
	}
}

Labeled for Loop

We can use a label before a for loop.

Syntax

label:

for(declare and initialization ; loop condition ; loop control increment/decrement){

//loop statements

}

Example

 
public class LabelForLoop {

	public static void main(String[] args) {
		outer:
			for(int i=0;i<5;i++) {
				inner:
					for(int j=0;j<5;j++) {
						if(i==3)
							break inner;
						System.out.println("Print i= " + i + " j= " +j); 
					}
			}
	}
}

Change the break statements to inner and outer and notice the change in the program output.

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version