How to Use the for each Loop in Java with Arrays

programmingIn any programming language, there are situations when we need to process a statement multiple times based on a particular condition. As an amateur programmer you would probably think of executing it for as many times you want in succession. But, what this technique is doing is cluttering the code. Any programmer knows a clean code is important to make debugging easier.

This is the reason looping was introduced in programming. Loops helps in completing repetitive tasks. In Java particularly, there are multiple looping operators. Let us have a quick look at the available options.

Learn more about how to use loops in Java at Udemy.com.

While loop

The Syntax for While loop is as follows –

while(Boolean_expression)

{

//Statements

}

This loop will execute when the Boolean expression is true. If the statement is false, the code will not enter the loop. The code will then go ahead with the statements that follow the while loop.

Here is an example of the while loop:

public class Test {

public static void main(String args[]) {
int i = 10;

while( i < 20 ) {
System.out.print("value of i : " + i );
i++;
System.out.print("\n");
}
}
}

Output:

value of i : 10
value of i : 11
value of i : 12
value of i : 13
value of i : 14
value of i : 15
value of i : 16
value of i : 17
value of i : 18
value of i : 19

do..while loop

The syntax for the “do…while” loop is as follows:

do
{
//statements to be executed
}while(Boolean_expression);

As you can see in the above code, the while statement that checks if the Boolean expression is true appears at the end of the “do” loop. This means the statements inside the loop are executed once before the expression is checked. If the statement is true, it will go back to the loop and execute the statements. But, if the statement if false, the loop ends and the flow continues with the next line of code after the While statement.

Here is a sample code for this loop:

public class Udemy {

public static void main(String args[]){
int u = 10;

do{
System.out.print("value of u : " + u );
u++;
System.out.print("\n");
}while( u < 15 );
}
}

Output:

value of u : 10
value of u : 11
value of u : 12
value of u : 13
value of u : 14
value of u : 15

New to Java programming? Take a course at Udemy.com.

for loop

The syntax for the “for” loop is as follows:

for(initialization; Boolean_expression; update)
{
//Statements
}

When you are aware about that a task needs to be repeated several times, you can use the “for” loop. It follows a structure where an integer is initialized, a condition is set with that integer, and then the integer is updated to a new value. Now, after initialization, the integer is checked for the Boolean expression. If found true, the code statements are executed. After this, the loop goes to the update statement and then again checks if the integer value satisfies the Boolean expression. If yes, the steps for loop execution are repeated until the Boolean expression becomes false.

Here is a sample example for this loop:

public class Udemy {

public static void main(String args[]) {

for(int n = 10; n < 15; n = n+1) {
System.out.print("value of n : " + n );
System.out.print("\n");
}
}
}

Output:

value of n : 10
value of n : 11
value of n : 12
value of n : 13
value of n : 14
value of n : 15

For each loop

Now, if you have noticed all the above examples, they are generally used to manipulate integers. What does one do when they have to work with iteration over arrays? To answer this question, in Java 5 was introduced the “For-each” loop. This loop can be used very well with iteration over arrays and other such collections. Though you can use a “for” loop with the iteration operator, the code becomes much more readable with for-each loop when dealing with huge numbers. This loop is preferred to the “for” loop, not always, but when the following conditions are seen:

  • Assigning elements: Avoid using for-each loop when you need to assign a value to an element. This loop can be used when only access is desired.
  • Use with single structure: You cannot use the loop when you need to compare two arrays in a situation.
  • Forward iterations only: Use the “for-each” loop only for forward looping and that too in single steps.
  • Compatibility: If you need your code to be compatible with versions before Java 5, you might want to go for the regular for loop.

 

Let us take a look at the syntax for this loop:

for(declaration : expression)
{
//Statements
}

Here, the declaration should be of the type of variable that you plan on accessing in the arrays. This variable will be used throughout the “for” block of code, and will be replaced each time with the array value that is being processed. The expression is nothing but evaluation of the array that we need to loop through. This expression generally is either an array variable or a method to return an array.

Sample code for this loop:

public class Udemy {

public static void main(String args[]){
int [] numericals = {100, 200, 300, 400, 500};

for(int u : numericals){
System.out.print( u );
System.out.print(",");
}
System.out.print("\n");
String [] titles ={"William", "Beatrice", "Lucy", "Sam"};
for( String name : titles ) {
System.out.print( name );
System.out.print(",");
}
}
}

Output:

100,200,300,400,500,
William,Beatrie,Lucy,Sam,

An important statement that we generally use with loops is the break statement. Use this statement to stop the loop. You can only use the statement inside the loop.

The syntax for the break statement is as follows:

break;

Here is a sample code for this statement:

public class Udemy {

public static void main(String args[]) {
int [] nums = {100, 200, 300, 400, 500};

for(int y : nums ) {
if( y == 300 ) {
break;
}
System.out.print( y );
System.out.print("\n");
}
}
}

Output:

100
200

Try tutorials at Udemy.com and become an expert in Java.