Java Loop Statements

In programming languages, loops are used to execute a set of instructions/functions repeatedly when some conditions become true.

for loop
while loop
do while loop
enhanced for loop

Loop Examples:

Fetching records (test data) from external source – like DB/ Excel file
Execute one block of code multiple times

1. for loop:

If the number of iteration is fixed, it is recommended to use for loop.

Syntax:

for(init;condition;incr/decr){
// code to be executed
}

Example: Lets print the numbers from 1 to 5.

for(int i=1; i<=5; i++){
  System.out.println("Printing using for loop. Count is: " + i);
 }

Printing using for loop. Count is: 1
Printing using for loop. Count is: 2
Printing using for loop. Count is: 3
Printing using for loop. Count is: 4
Printing using for loop. Count is: 5

2. while loop:

If the number of iteration is not fixed, it is recommended to use while loop.

Syntax:

while(condition){
//code to be executed
}

Example: Lets print the numbers from 1 to 5.

int i=1;
while(i<6){
   System.out.println("Printing using while loop. Count is: " + i);
}

Printing using while loop. Count is: 1
Printing using while loop. Count is: 2
Printing using while loop. Count is: 3
Printing using while loop. Count is: 4
Printing using while loop. Count is: 5


3. do while:

If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop.

Syntax:

do{
//code to be executed
}while(condition);

4. Enhanced/for-each loop

In Java, there is another form of for loop (in addition to standard for loop) to work with arrays and collection, the enhanced for loop.

Syntax:

for(Type var : arrayname){
//code to be executed
}

To get more details please watch below youtube video and Subscribe the channel.



No comments:

Post a Comment