One of the basic element of a programming language is its loop control. It’s ability to iterate over a collection of elements and then get the desired result. In java, this is no different than any other programming languages such as C and C++. Like for instance we want to print all elements of an array or other java collections, we will be using loops to iterate through the array contents and then print one by one.

On this java tutorial we will be showing different ways and scenarios on every single available loop statements in java. We will be showing as well on the usage of break and continue in combination with different loop statements. To add more spice, we will be using as well on some examples the combination of loops and conditional statements.

There are 4 loop statements in java. These are the following:

  • while
  • do while
  • for
  • for each

The while loop

The while statement continues to execute a block of statements while the condition specified is still true.

while loop Syntax:

while (boolean_expression) {
statement(s)
}

the boolean_expression must be evaluated to boolean data type which means it should be equal to true or false. In order for the loop to iterate over the statement(s) specified, the expression must be be evaluated to true. The loop will continue to evaluate the statement block/s until the boolean_expression is still true or we have not yet invoked the break statement. More on the break statement later on this document.

while Loop Example:

Let’s take an example scenario wherein we want to sum up numbers from 1 t0 20. Instead of doing 1+2+3…+n which requires a lot of effort and patience to do so. And what if the range changes dynamically? The while loop will come in handy to handle situation like this.

package com.javatutorialhq.java.examples;

/*
 * This java example source code 
 * shows how to use the while loop
 * to get the sum of number range
 */

public class WhileLoopSum {

	public static void main(String[] args) {
		// declare the iteration variable
		int i = 0;
		// declare the sum holder
		int sum =0;
		// loop until i is less than 5
		while(i<5){
			/*
			 * statment blocks
			 */
			// initial value of i plus one
			i++;
			// add the value of i to the current sum value
			sum = sum+i;
		}
		// print the sum result
		System.out.println("Sum:"+sum);
	}

}

Running the program above will give you the following output:

Sum:15

The example above will give the sum of numbers 1 to 5. Initially we assign a variable i to 0. and we put the boolean expression on the while as i < 0. And inside the while loop our intention is to increase the number of i by 1 and then at the same time we would add the value to the sum variable. The increasing of variable value to can easily be done using the increment operation i++. And then we could gather the sum value by adding the previous value of sum to the current value of i. This example become tricky given that we have initially initialized the value of i to be 0 and the boolean_expression on the while loop is i < 5. If we follow the looping, the value of i would be 0,1,2,3,4 and the loops terminates. Then we will be missing the 5 and then we have added 0 on getting the sum. That’s why on the solution presented above, we have done the following:

while(i<5){			
	i++;			
	sum = sum+i;
}

the i++ is cleverly placed before the operation in getting the sum because of the initial value of i which starts at 0 and also considering the boolean_expression that would only be true if i is less than 5. So what if we have initially initialized the value of i to 1. We should be having the following code block instead of the above implementation:

while(i<=5){			
	sum = sum+i			
	i++;
}

Even though we have different implementation of the while loop, it would achieve the desired result. You might be asking which one is better? Depending on the situation, the business requirements and your coding style and preference, you might opt to select any of the two approach. It’s just a matter of preference.

while loop and break statement

What if we want to continuously do the loop until a certain condition has been meet outside the boolean expression declared on the while loop? On this kind of scenario, the break statement becomes handy. The following code block is one way to do an infinite loop and then at some point we terminate it.

		while(true){
			//do what you want here
			if(condition statement){
				//if the condition has been met exit the loop
				break;
			}
		}

Make sure to properly watch for loops which will not terminate at all (infinite loop). It’s a common mistake for beginners in java programming and will result problems like out of memory error.

The do while Loop

This looping mechanism in java as the statement suggest that it will do first a statement block while the boolean_expression evaluates to true. The syntax is conveniently structured, for us not to get confused.

do while Loop Syntax

do {
statement(s)
} while (boolean_expression);

the boolean expression on the while parameter must be evaluated to boolean true or false. Basing on the structure of the do while loop, even the boolean_expression is evaluated to false, the code block inside the do statement will get evaluated at least once. Let’s take the same example as that on the while loop for you to differentiate the two.

do while Loop Example

package com.javatutorialhq.java.examples;

public class DoWhileLoopSum {

/*
 * This java example source code
 * demonstrate the use of do while loop
 * to get the sum of specific number range
 */
	public static void main(String[] args) {
		// initialize the variables
		int sum=0;
		int i=0;

		do{
			// increment the value of i
			i++;
			// add the value of i to the existing value of sum
			sum = sum+i;
		}
		while(i<5);
		System.out.println("sum:"+sum);

	}

}

Running the program above will give the following output:

sum:15

As you would already have notice the example provided is exactly the same example as that of the while loop. As already mentioned, the initial value of i and the placement of i++ is strategically placed. You might be asking now which is better the while loop or the do while loop? For me it is a matter of preference and coding style. Whatever you have chosen, as long as it you are comfortable working on it, you will be fine.

do while loop and break statement

Similar to while loop, the break statement is also applicable for do while loop. This is necessary to implement if we stumble on a scenario wherein we continuously need to loop until a certain condition has been met. The only difference with the while loop is that on do while, the statement block inside the do will be executed at least once. Let’s take the following code block to further visualize as such scenario

		do{
			statement(s);
			if(condition_statement){
				break;
			}
		}
		while(true);

The for Loop

The for statement continuously executes the code block until a certain condition statement has been met which is specified inside the for loop or it is terminated by break statement. This is one of my favorite since the initialization, the condition and iteration is declared on one line. Not unlike in while loop that we have to declare the values separately.

for Loop Syntax

		for (var_intialization; boolean_expression;increment/decrement) {
			    statement(s)
		}

As you would have noticed on the code block above the initialization of iteration variable is done inside the for loop statement not unlike in the while loop and do while which is done before the actual loop statement. The var_initialization is executed once as the for loop begun. The boolean_expression must result to true for the loop to start. The increment/decrement is invoked after each and every iteration occurs. You might be asking why a decrement statement is included? The looping can also be done by decrementing the iteration element.

Let’s take for an instance the requirement is to start on a value greater than 1 and then as you move along the iteration decrement by 1. Don’t get confused on this, this is no different in handling the increment, just on this case instead of going up, we are going down. For you to visualize this, let me give one concrete example. Let’s take an instance wherein we have an array of strings and then we want to print the values in reverse order. On this kind of scenario instead of starting on the first element of the array we should start at the end of the array thus a decrement scenario is likely a good approach. See below example:

for Loop Example

package com.javatutorialhq.java.examples;

/*
 * Java Example source code example on for loop
 * Print an array in reverse using for loop
 */

public class ForLoopArray {

	public static void main(String[] args) {
		// intialize the array elements
		int[] arrayInt = new int[]{1,2,3,4,5};
		// loop control
		for(int i=arrayInt.length-1;i>=0;i--){
			// Print each element of an array
			System.out.println(arrayInt[i]);
		}

	}

}

Running the code above will give the following output:

5
4
3
2
1

Given the example above variable i is initialized to the length of the the array -1 because an array index starts at 0. And it is my intention to use the i– thus, i am forced to decrement 1 on the array length on initialization. Depending on your coding style, this might not be true on your case. To fully utilize the power of these loops, all those basic rules on indexing and sequential programming must be established first which is already out of scope on this document. Moving back on the discussion, from the example above we can actually do the i initialization before the the for loop. And the i– can be done after printing the array element.

		int i=arrayInt.length-1;
		for(;i>=0;){
			// Print each element of an array
			System.out.println(arrayInt[i]);
			i--;
		}

The above code will achieve the same result as the previous one. And have you noticed? This would be the same as the while loop. So basically the for loop is also a while loop in a certain way. It’s only a matter of understanding and mastery of the rules in java programming loops.

The for each Loop

The for each loop is widely used in dealing with arrays, list and other collections. It is sometimes called advanced/enhanced for loop because this is only been introduced on JDK 1.5. To put it in simple language, “for each element of a collections do the following code block”.

It is a java recommendation that the for each loop must be used instead of the legacy form whenever possible.

for each Example

package com.javatutorialhq.java.examples;

/*
 * Java Example source code example on for each loop
 * Print an array using advanced for loop
 */

public class ForEachLoopArray {

	public static void main(String[] args) {
		// intialize the array elements
		int[] arrayInt = new int[]{1,2,3,4,5};

		for(int element:arrayInt){
			// print each element of the array
			System.out.println(element);
		}

	}

}

The code above simply prints all the elements of an array using the for each loop. Using the for each loop, the declaration is simplified. Unnecessary mistakes in indexes and iteration variable declaration is eliminated using the for each loop. It makes java programming easier and less complicated to java beginners.