In this tutorial, we are going to discuss Java Foreach loop and for loop but before starting it you have to know what is looping. Looping is a process means it repeats a statement or group of statement again and again until it reaches the given condition.

Java For Loop and Foreach Loop with Examples

Java for Loop

For loop is used to execute a statement or group of a statement or group of statement repeatedly. Java for loop is also known as the definite loop.

Java for Loop Syntax:

for(initialization;test-condition;increment/decrement)
{
//statement will be here
}

the for loop statement takes three parameters-

initialization- we initialize the value for the loop counter.

condition- here we give the condition if the value of condition is true then the loop statements execute.

increment/decrement- the update expression increment/decrement executes.

Java for Loop Example:

Let’s see the following example of for loop-

public class DemoFor {  
public static void main(String[] args) {
for(int i=1;i<=5;i++)
{
System.out.println("number is:"+i);
}
}
}

this program will produce the following-
Output:

Number is: 1 
Number is: 2
Number is: 3
Number is: 4
Number is: 5

Infinite For Loop

If the test condition will always true then it is called infinite for loop. Let’s see the example-

for( ; ; ;)
{
}

initialization, test condition, and increment/decrement expression in for loop statement are optional.

Java Foreach Loop

Java Foreach loop is an advanced loop which allows you to iterate over in an array. There is two way to implement the Java Foreach loop.

Java Foreach Loop Syntax:

foreach(type variable_name : collection/array)
{
//statement will be here
}

Java Foreach Loop Example:

Let’s see this example how Java Foreach loop works and by it, you will understand how to works with Foreach loop-

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

int[] prime= {1,3,5,7,9};
// foreach loop
for (int num: prime ) {
System.out.println("prime Number is:"+num);
}
}
}

After the execution of the program, it will produce the following output-

prime Number is: 1 
prime Number is: 3
prime Number is: 5
prime Number is: 7
prime Number is: 9

there are four loops in Java, next two looping methods you will learn in our tutorial while loop.