Java for loop

Is it right to say that a good programmer must have a deep understanding of loops? That might be a yes or no question but also lacks meaning without justification. In short, what are loops? A loop is a program that Iterates/ repeats several times until a specific condition is met. Loops remain the same no matter the programming language you are using.

The Purpose of loops

Let’s say you need to display a message 500 times, and it is very tiresome and time-consuming to type the same message 500 times, which is why loops are so important. You can write the message once and loop through 499 times within only a few lines of code. This the power of loops.
Example:

package javaforloops;

public class JavaForLoops {
    public static void main(String[] args)
    {
        System.out.println("=====Using normal program ======");
        int numbers; 
        numbers = 1; 
        System.out.println(numbers); 
        numbers=2; 
        System.out.println(numbers); 
        numbers=3; 
        System.out.println(numbers); 
        numbers=4; 
        System.out.println(numbers); 
        numbers=5; 
        System.out.println(numbers); 
        
        //using java for loop
        System.out.println("======Using for Loop=======");

    for(int i=1;i<=5;i++)
    {
        System.out.println(i);
    }
    }
    
}

Output:

run:
=====Using normal program ======
1
2
3
4
5
======Using for Loop=======
1
2
3
4
5
BUILD SUCCESSFUL (total time: 0 seconds)

In the above code, the first section shows a normal java code with no for loop while the second part uses for loop to output the same results. What are some of the disadvantages of not using the for loop?

  • Repetition of code: It’s good and recommended to avoid code repetition as much as possible as a good programmer. What if we had like 100 messages? We will repeat the same message 100 times; this is an unnecessary code.
  • Fixed code: The code is fixed to print only 1-5. If we need a certain pattern, we will write another program again with a fixed structure written repetitively.
  • Scalability: The code is not scalable. If we need to print 1-10, we will add 5 more code lines and use the for loop. We only need to change the range to 10. The for loop is highly scalable.

Types of Loops

There are 3 types of loops.

  • For loop
  • While loop
  • Do-while loop

We use a for a loop when we know the specific number of times we need to Iterate through a block of code and a while loop when we are not sure of the number of times we need to loop through a code block.  We use it for a do-while loop when we have to execute the loop at least once.

With that bit of introduction, let’s know dig in to java for loop.

Java for Loop.

As we mentioned earlier, we use java for a loop when we know the exact number of times you need to loop through a block of code.

Syntax of java for loop

for (statement 1; statement 2; statement 3)
{
  //The java for loop code to be executed goes here
}

Types of java for loops

There are 3 types of for loops in java. These includes
1. Simple for loop
2. For-each loop/Enhanced for loop
3. Labeled for loop

Simple for loop

Syntax of a simple for loop

for(initialization; condition; increment/decrement)
{
  //the code of the simple for loop goes here
}

Initialization: This is the first part of the java for loop that we declare and initialize a variable by assigning it a value. It’s the initial condition that is executed one time before the for loop block of code execution.
Example:

Int k = 0;

Condition: This the second part that forms the condition, it returns a boolean value ‘true’ or ‘false’. This means if the condition is true, the loop will start over again and if the condition is false the loop terminates.
Example:

K <= 100; or K >= 100;

Increment/Decrement: This the part that adds values or decreases values in the for loop. Its executed every time after the block of code execution.
Example:

//Increment
K++
//decrement
K--

Flow chart for a simple java for loop

Simple for loop
Simple for loop flowchart

Example of Java Simple For Loop

package javaforloops;

public class JavaForLoops {
    public static void main(String[] args)
    {
    for(int i=0;i<=2;i++)
    {
        System.out.println("I Have Understood a simple java for loop");
    
    }
    }
    
}

Output:

run:
I Have Understood a simple java for loop
I Have Understood a simple java for loop
I Have Understood a simple java for loop
BUILD SUCCESSFUL (total time: 0 seconds)

In the above simple java for loop example, in the initialization part, we have declared a variable i and initialized it to 0. So it comes to loop body to print “I have Understood a Simple Java for loop” when the condition is less than or equal to 2, and then it moves to increment a value by 1.

Suppose the result in the condition part is true. The loop prints the message and increments its value by 1. When the condition is false, i=3 and 3<=2 (is false), the loop terminates.

At times you may have more than one argument in the condition part to check the condition. We cannot separate the two conditions by a comma, but we can use the ‘AND’ or ‘OR’ conjunctions.

package javaforloops;

public class JavaForLoops {
    public static void main(String[] args)
    {
        int b = 4, c = 5;
    System.out.println("=== Conjuction AND ===");
    for(int a=2;a<=b && a<=c ;a++)
    {
        System.out.println("Hello java");
    
    }
    System.out.println("=== Conjuction OR ===");
    for(int a=4;a<=b || a<=c ;a++)
    {
        System.out.println("Hello java");
    
    }
    }
    
}

Output:

run:
=== Conjuction AND ===
Hello java
Hello java
Hello java
=== Conjuction OR ===
Hello java
Hello java
BUILD SUCCESSFUL (total time: 0 seconds)

For-each for loop/Enhanced for loop

To loop through elements in an array or a collection, we use a for-each loop or enhanced for loop. In this loop, we do not require the incremental/decremental part.

Syntax

//array
for(variable type : array)
{
//code to be executed
}
//collection
for(object var :Collection )
{
//code to be executed
}

Example of an enhanced for loop

package javaforloops;
public class JavaForLoops {
    public static void main(String[] args)
    {  
	int arr[]={100,101,102,103,110};  
	//Printing array using for-each loop  
	for(int array:arr){  
	 System.out.println(array);  
	}
    } 
}

Output:

run:
100
101
102
103
110
BUILD SUCCESSFUL (total time: 0 seconds)

Are there any advantages to looping through an array using an enhanced for loop rather than a simple java for loop? An enhanced java for loop simplifies the work, but it is immutable. In a simple for loop, you can alter the values inside the loop, but in an enhanced for loop, the object used for transversing is immutable. Let’s look at this by using an example.

package javaforloops;

public class JavaForLoops {
    public static void main(String[] args)
    {  
	 String array[] = { "Java", "Python", "Html", "Machine Learning" }; 
        // enhanced for loop 
        for (String languages : array) { 
            System.out.println(languages); 
        } 
        // for loop for same function  
        for (int languages = 0; languages < array.length; languages++)  
        {  
            System.out.println(array[languages]);  
        }  
    }
}

Java Labeled for loop

In a nested for loop, we may decide to have a name for the java for loops. We use a label before the loop, and this forms the java labeled for a loop. It’s mostly used nested for loop to break or continue from the specific “for” loop with the help of the label.

Syntax

LabelName:
for(initialization; condition; increment/decrement)
{
//code to be executed
}

Example of a labeled for loop

package javaforloops;

public class JavaForLoops {
    public static void main(String[] args)
    {    
       Loop1:  
       for(int i=1;i<=2;i++){  
              Loop2:  
                  for(int j=1;j<=2;j++){  
                      if(i==2 && j==2){  
                          break Loop1;  
                      }  
                      System.out.println(i+" "+j);  
                  }  
    }
    }   
}

Java Infinitive for loop

Java infinitive for loop code runs continuously without an end until the memory runs out.
At times we use (;;) to indicate java infinitive java for loop. The condition part will never return false for the loop to terminate.
Example:

package javaforloops;
public class JavaForLoops {
    public static void main(String[] args)
    {    
        for(int k =2 ; k >= 2; k++){
              System.out.println("The value of i is: "+k);
         }

    }   
}

The initialization part is declaring a variable K and initializing it to 2. Then we check for the value of K to be equal to or greater than K. Since we are incrementing the value of K, it would always be greater than 2; hence the Boolean expression (K >= 2) would never return false. This will lead to an infinitive loop condition.

Java Nested for Loop

This is looping inside another loop. For the outer loop to execute, the inner loop must execute completely.
Example:

package javaforloops;
public class JavaForLoops {
    public static void main(String[] args)
    {    
       	for(int i=1;i<=5;i++)
        {  
	for(int k=1;k<=i;k++)
        {  
	        System.out.print("* ");  
	}  
	System.out.println(); 
	}  
    }   
}

In the above example, in the first loop, we initialize i to 1, the loop prints a new line as long as the lines are less than or equal to fine (i<=5). In the nested loop, we initialize k to 1. The loop executes and prints (*) as long k<=i. we close the inside loop before closing the outer loop. It’s important to nest the loops to get the desired output.

How to use continue in java for loop.

The continue statement is mostly used in for loop to jump immediately to the beginning of the next iteration of the loop.

Continue flowchart diagram
Continue flowchart diagram


Example

package javaforloops;
public class JavaForLoops {
    public static void main(String[] args)
    {    
     int [] numbers = {1, 2, 3, 4, 5};

      for(int k : numbers ) {
         if( k == 4 ) {
            continue;
         }
         System.out.println( k );
         
      }
  
    }   
}

Output:

run:
1
2
3
5
BUILD SUCCESSFUL (total time: 0 seconds)

From the output of the code above, the output value 4 is missing, yet we have initialized it in our array. This is because as the code executes and when the continue statement is encountered, it jumps at the beginning of the loop for the next iteration, thus skipping the current iteration statement. At this point, we can say the block of code to println did not execute when k was equal to 4.

How to use break in java for loop

The break statement is used when we want to jump out of the for loop.
Example.

package javaforloops;
public class JavaForLoops {
    public static void main(String[] args)
    {    
     int [] numbers = {1, 2, 3, 4, 5};

      for(int k : numbers ) {
         if( k == 4 ) {
            break;
         }
         System.out.println( k );
         
      }
  
    }   
}

Output:

run:
1
2
3
BUILD SUCCESSFUL (total time: 0 seconds)

From the output of the code above, the output values 4 and 5 are missing, yet we have initialized them in our array. This is because the loop terminates when it reaches the condition where k was equal to 4.

Conclusion

Summing up, In this tutorial, we have learned about java for loops, their syntax, and types. We have also gone ahead and looked at the infinitive loop, nested loop, break statement in the for loop, and continue statement in the java for loop. Point to note, Variables declared inside a for loop are local variables, and we cannot access them after the loop’s termination. This is because variables declared inside a block of statement its scope is only within the block.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *