Java for Loops…

Java Tutorial – Java for Loops…

In this tutorial we will discuss one of the three basic looping constructs — the Java For Loop. We will discuss the syntax of the for loop, definition and initialization of the loop, boolean expression, and loop iteration.

What’s Covered

  1. What is the For Loop?
  2. For loop Syntax
  3. For loop Example
  4. For loop Output
  5. Infinite Loop using For
  6. Infinite Loop Output
  7. For Loop Variations
  8. Infinite Loop using For (Logic Bug)
  9. For loop Output (Logic Bug)
  10. For loop — Stop Conditions
  11. Break Statement
  12. Labeled Break Statement
  13. Labeled Break Statement Output
  14. Continue Statement
  15. Continue Statement Output
  16. Labeled Continue Statement
  17. Labeled Continue Statement Output
  18. Java 5 Enhanced For Loop
  19. Java 5 Enhanced For Loop Output

What is the For Loop?

The for statement provides a mechanism to allow us to repeat a set of java operations while the condition is true. The for statement starts with initialization, followed by a boolean expression evaluation, and finally a update statement to either increment or decrement the variable used in the looping structure.

For loop Syntax

for (initialization; boolean condition; update_statements) {
   statement;
   statement;
   ...
}

Key points when using this version of the for loop:

  • The initialization statement initializes the loop when the loop begins (only executed once).
  • The loop continues as long as the boolean condition evaluates to true; as soon as it becomes false the loop ends.
  • The update_statements can either increment or decrement the value after each iteration through the loop.

For loop Example

In the following example, the for loop does the following:

  • initialize int i=0
  • check the condition; is the value of i is less than 5
  • increment i by 1. i++ is the short version of i=i+1
public class ForLoopExample {
 public static void main(String[] args) {
  for (int i=0; i<5; i++) {
   System.out.println("value of i=" + i);
  }
 }
}

For loop Output

value of i=0
value of i=1
value of i=2
value of i=3
value of i=4

As you can see from the example above, our for loop is initialized to zero (0), our boolean expression i<5 is evaluated and is true the update statement i++ is executed incrementing i to 1 after the statement block is executed. This looping will continue while the boolean expression evaluates to true.

For Loop Variations

Since all three parts of the for loop are optional, we can rewrite the for loop in a number of different ways. In this example below, we will leave out the optional initialization part. The variable k is declared outside the loop, enabling variable k to be used outside of the for statement block.

public class ForLoopExample {
 public static void main(String[] args) {
  int k = 0;
   for ( ; k<5 ; k++) {
    System.out.println("value of k=" + k);
   }
   // k is still in scope here
 }
}

In this next example, we leave out the optional update statement and we perform the increment inside of the statement block.

public class ForLoopExample {
 public static void main(String[] args) {
  int k = 0;
  for ( ; k<5 ; ) {
     System.out.println("value of k=" + k);
     k++;
  }
 }
}

Infinite Loop using For

One way we can create an infinite loop is by leaving the three optional expressions in the for statement empty.

for ( ; ; ) {
   statement;
 }
public class ForLoopExample {
 public static void main(String[] args) {
  int i = 0;
  for ( ; ; ) {
   System.out.println("value is " + i);
   i++;
  }
 }
}

Infinite Loop Output

value is 0
value is 1
value is 2
value is 3
value is 4
value is 5
value is 6
value is 7
...

Infinite Loop using For (Logic Bug)

Additionally, we could create an infinite loop inadvertently by using an incorrectly laid out booleanExpression. In this example, our i<11 condition will never be false as every new value is also less than 11. In actuality, this loop will continue until we hit the minimum value for integer which is Integer.MIN_VALUE or -2147483648 (2^31-1).

public class InfiniteForLoopExample {
 public static void main(String[] args) {
   for (int i=10; i<11; i--) {
    System.out.println("value of i=" + i);
   }
 }
}

For loop Output (Logic Bug)

value of i=10
value of i=9
value of i=8
value of i=7
value of i=6
...

For loop — Stop Conditions

The following conditions will trigger the for statement to stop:

  • if our booleanExpression evaluates to false
  • a break statement is executed
  • a continue statement is executed
  • a runtime error or exception occurs

Break Statement

The break statement is used to break out of for, while, do-while and switch statements. There are two forms of the break statement: labeled and unlabeled.

public class BreakForLoopExample {
 public static void main(String[] args) {
  for ( int j=0; j < 10; j++) {
    System.out.println("value of j=" + j);
    if (j >= 4)  
      break;
  }
 }
}

Break Statement Output

As you can see below, the break statement terminates the for loop when the value of j is greater than or equal to 4 as denoted by the j>=4 if condition.

value of j=0
value of j=1
value of j=2
value of j=3
value of j=4

Labeled Break Statement

The break statement terminates the for loop which includes the labeled statement. Control is transfered to the statement immediately following the terminated labeled statement.

Labeled Break/Labeled Continue

In general, I would recommend that you avoid the use of labels as much as possible. Please use them sparingly and with caution.

public class LabeledForLoopExample {
 public static void main(String[] args) {
  begin:
  for ( int j=0; j < 5; j++) {
   for ( int k=0; k < 5; k++) {
      System.out.println("value is " + j + ':' + k);
      if (j == 1 && k == 2)
       break begin;
   }
  }
 }
}

Labeled Break Statement Output

In this example, we use two for loops iterating from 0 through 4 for both the inner and outer loops. Within the inner loop we have println statement to print out the value of variable j and k. Note that the break statement breaks the loop if j equals 1 and k equals 2.

value is 0:0
value is 0:1
value is 0:2
value is 0:3
value is 0:4
value is 1:0
value is 1:1
value is 1:2

Continue Statement

The continue statement is similar to break except that it only stops the execution of the current iteration of for, while or do-while loops.

public class ForLoopExample {
  public static void main(String[] args) {
    for ( int j=0; j < 5; j++) {
      for ( int k=0; k < 5; k++) {
        if (k == 2)
          continue;
        System.out.println("value is " + j + ':' + k);
      }
    }
  }
}

Continue Statement Output

In this example, you will notice that the if statement checks k and if it has a value of 2 it will execute the continue statement and skips the println statement. In the output below, you will note that every value of k where it equals 2 is left out of the execution.

value is 0:0
value is 0:1
value is 0:3
value is 0:4
value is 1:0
value is 1:1
value is 1:3
value is 1:4
value is 2:0
value is 2:1
value is 2:3
value is 2:4
value is 3:0
value is 3:1
value is 3:3
value is 3:4
value is 4:0
value is 4:1
value is 4:3
value is 4:4

Labeled Continue Statement

In Java, continue may also be followed by a label as was the break statement. In our example below, we will continue to the outer loop once our condition, that is, when j is equal to 1 and k is equal to 2, is met.

public class ForLoopExample {
 public static void main(String[] args) {
  begin:
  for ( int j=0; j < 5; j++) {
   for ( int k=0; k < 5; k++) {
      System.out.println("value is " + j + ':' + k);
      if (j == 1 && k == 2)
       continue begin;
   }
  }
 }
}

Labeled Break Statement Output

value is 0:0
value is 0:1
value is 0:2
value is 0:3
value is 0:4
value is 1:0
value is 1:1
value is 1:2
value is 2:0
value is 2:1
value is 2:2
value is 2:3
value is 2:4
value is 3:0
value is 3:1
value is 3:2
value is 3:3
value is 3:4
value is 4:0
value is 4:1
value is 4:2
value is 4:3
value is 4:4

Java 5 Enhanced For Loop

Java 5 introduced an enhanced for statement. This enhanced for loop may be used to iterate over collections and arrays. Use of this form can make ypour code easier to read and more maintainable.

for ( type variable : collection ) {
   statement;
 }

Where type is the element type of the array or collection, variable is a reference to the elements in the array or collection and colleciton is the reference to the array or collection.

public class EnhancedForLoopExample {
 public static void main(String[] args) {
  String names[] = {"Amaury", "John", "James", "Marie"};
  for (String name : names) {
   System.out.println("value is " + name);
  }
 }
}

Java 5 Enhanced For Loop Output

value is Amaury
value is John
value is James
value is Marie

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

java_forloops

Core Java Related Tutorials

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

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