Master java skills

Control Statements – Loops

A loop means repetition of code as long as a condition is fulfilled. Following types of loops are under scope for this chapter:

  1. while loop
  2. do while loop
  3. for loop
  4. for-each loop

While Loop

While loop example is given below

package com.javatrainingschool;

public class WhileLoopExample {
	
    public static void main(String[] args) {
		
        int counter = 0;
	while (counter < 10) {
	    System.out.println("value of counter is : " + counter);
	    counter ++;
	}
    }
}
Output :

value of counter is : 0
value of counter is : 1
value of counter is : 2
value of counter is : 3
value of counter is : 4
value of counter is : 5
value of counter is : 6
value of counter is : 7
value of counter is : 8
value of counter is : 9

Do while loop

The only difference between while and do-while loop is that, if the condition inside while loop is not true, then the loop will not run even once. Whereas in case of do-while loop even if the condition is false, then also the loop will run once. Let’s consider below example

package com.javatrainingschool;

public class DoWhileLoopExample {
	
	public static void main(String[] args) {
		
		int counter = 7;
		do {
		     System.out.println("value of counter is : " + counter);
		     counter ++;
		} while (counter<5);
	}
}
Output :
value of counter is : 7

In the above example, while condition fails even before the first iteration, still the loop runs once because that’s the natural behaviour of do-while loop example

Note -> Use do-while loop in a scenario where you want the loop to run at least once even if the condition is not true.

For Loop

The syntax for ‘for’ loop is as follows:

for (initialization ; condition ; increment/decrement) { //some code here }

package com.javatrainingschool;

public class ForLoopExample {

	public static void main(String[] args) {
		for(int counter = 1; counter < 5; counter ++) {
			System.out.println("For loop running. Iteration number : " + counter);
		}
	}
}
Output : 
For loop running. Iteration number : 1
For loop running. Iteration number : 2
For loop running. Iteration number : 3
For loop running. Iteration number : 4

Nested For Loops

For loops can also be nested. Let’s see one example

package com.javatrainingschool;

public class ForLoopExample {

	public static void main(String[] args) {
	    for(int i = 1; i < 5; i ++) {
	        for(int j = 1; j <= i; j++) {
		    System.out.print("*");	
		}
		System.out.println();
	    }
	}
}
Output:

*
**
***
****

For-each Loop

For-each loops are used to traverse a collection type object like list, set and arrays.

syntax of For-each loop

for (data-type <var-name> : list) { //some code here }

For-each example for arrays :

package com.javatrainingschool;

public class ForEachLoopExample {

	public static void main(String[] args) {
		
		String [] names = new String[] {"Arjun","Shankar","Javed"};
		for(String name : names) {
			System.out.println("Name is : " + name);
		}
	}
}
Output :
Arjun
Shankar
Javed

For-each example for list :

package com.javatrainingschool;

import java.util.ArrayList;
import java.util.List;

public class ForEachLoopExample {

	public static void main(String[] args) {
		
		List<String> names = new ArrayList<String>();
		names.add("Meera");
		names.add("Kabir");
		names.add("Raidas");
		for(String name : names) {
			System.out.println("Name is : " + name);
		}
	}
}
Output :
Name is : Meera
Name is : Kabir
Name is : Raidas

Branching/Jump Statements

There are certain situation when we want our loop to control in our own way. There are two statements given for this purpose. Break, Continue. Let’s understand both with examples

Break statement

Break statement, when encountered, breaks the loop and comes out of it. In the below example, the loop will break when the value of counter becomes 3.

package com.javatrainingschool;

public class ForLoopExample {

	public static void main(String[] args) {
		for(int counter = 1; counter < 5; counter ++) {
			System.out.println("For loop running. Iteration number : " + counter);
                        if(counter == 3)
                           break;
		}
	}
}

In the below output, we can see that loop breaks and doesn’t execute after counter is equals to 3.

Output :
For loop running. Iteration number : 1
For loop running. Iteration number : 2
For loop running. Iteration number : 3

Continue Statement

Continue statement, when encountered, continues the loop for that iteration and doesn’t execute loop statements after the ‘continue’ keyword for that iteration. It, however, runs the next iteration. Below example explains that.

Note -> If block doesn’t require curly braces if there is only one statement. As you can see in the below example.

package com.javatrainingschool;

public class ForLoopExample {

	public static void main(String[] args) {
		for(int counter = 1; counter < 5; counter ++) {
		   System.out.println("For loop running. Iteration number : " + counter);
                   if(counter == 3)
                      continue;
                   System.out.println("For loop second statement");
		}
	}
}

In the output, we can see that – For loop second statement – is not printed for iteration 3 when the value of counter is equal to 3.

Output :
For loop running. Iteration number : 1
For loop second statement
For loop running. Iteration number : 2
For loop second statement
For loop running. Iteration number : 3
For loop running. Iteration number : 4
For loop second statement