For Loop


This image has an empty alt attribute; its file name is image-9.png

Hi there, let’s look at the Java For Loops! Java has looping statements as part of the control flow statements.  There are three different looping statements; for, while, and do while. 

In this post , we will focus only on the “for loop” statement and the other two will be our learning topics  in the coming post after this one.

 Java for loop statement that is used to run a block of code if the number of iteration is fixed.  If the number of iteration is not fixed,  there is while loop and do while loop to be used.  

Let’s understand the syntax required for the code first;

for (initial statement; second statement; increment/decrement){    

//Block of code 

}  

Initial statement: Initial condition which is executed one time when the loop starts

Second statement: Second condition which is executed each time when the loop starts

increment/decrement: Increment or decrement of values, example; ++x, –x, +2x, or x++,x–,x+2 (check “Operators” post to refresh your knowledge)

Example 1: Print values between -1 to -5

Example 2: Nested loop, you can have a loop inside of other loop

As you might remember,  we saw some string methods with some arrays involved.  Java array is an object with elements of similar data types. Square blankets are used to declare an array.

Examples:

String [ ] fruits;

String [ ] fruits = { “Apple”, “Banana”, “Pear”};

Int [ ] myNum = {1, 2, 3, 4, 5};

Loops also “for each” loop that could be used with arrays. Syntax of code is like following;

for (type variable : array name){    

//block of code   

} 

I hope you have learnt about for loop statement. Next time we will go over While & Do While Loops statements.

Leave a comment