The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the «for loop» because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) < statement(s) >
When using this version of the for statement, keep in mind that:
- The initialization expression initializes the loop; it’s executed once, as the loop begins.
- When the termination expression evaluates to false , the loop terminates.
- The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
The following program, ForDemo , uses the general form of the for statement to print the numbers 1 through 10 to standard output:
The output of this program is:
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10
Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it’s best to declare the variable in the initialization expression. The names i , j , and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors.
The three expressions of the for loop are optional; an infinite loop can be created as follows:
The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:
The following program, EnhancedForDemo , uses the enhanced for to loop through the array:
class EnhancedForDemo < public static void main(String[] args)< int[] numbers = ; for (int item : numbers) < System.out.println("Count is: " + item); >> >
In this example, the variable item holds the current value from the numbers array. The output from this program is the same as before:
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10
We recommend using this form of the for statement instead of the general form whenever possible.
Java for, while, do..while & foreach loops iteration control statements Tutorial
In this Java tutorial we learn how to repeat sections of our code with while, do while, for and foreach (enhanced for) loops based on the results of a condition.
We also discuss nesting loops. Lastly, we learn how to refine control on our loops by using the break and continue statements.
What is iteration control and looping
Java allows us to control the flow of our application even further by looping through sections of code when a condition proves true.
As an example, let’s consider a database of users that are subscribed to a mailing list.
Normally, we would enter a user’s email address, copy-paste a predefined message, and then send the email.
But, there could be tens of thousands of users in that list. We would need a way to automate the process.
Iteration control allows us to set up that process in code, then repeat it by looping through all the users on the list, sending them each an email.
Java provides us with four different kinds of loops:
- while — This loop iterates through a section of code while a condition is true.
- do while — This loop is the same as the while loop but with a single forced loop at the start.
- for — This loop iterates through a section of code a set number of times.
- foreach — This loop is specific to loop through collections.
The indefinite while loop in Java
A while loop is used when we don’t know how many times a loop will repeat, like the number of users in a database.
A while loop will keep looping through its code, while a specified condition is true. For example, while there are users in a database, loop through the section of code that sends an email.
To write a while loop, we use the keyword while , followed by the condition in between parentheses, and a code block that contains the code we want to execute on each iteration.
Loops in Java
Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time.
java provides Three types of Conditional statements this second type is loop statement .
- while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
Java
- Flowchart:
- While loop starts with the checking of Boolean condition. If it evaluated to true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason it is also called Entry control loop
- Once the condition is evaluated to true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.
- When the condition becomes false, the loop terminates which marks the end of its life cycle.
- for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
for (initialization condition; testing condition;increment/decrement)
Java
- Flowchart:
- Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.
- Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
- Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.
- Increment/ Decrement: It is used for updating the variable for next iteration.
- Loop termination:When the condition becomes false, the loop terminates marking the end of its life cycle.
- do while: do while loop is similar to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of Exit Control Loop.
Java
- Flowchart:
- do while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.
- After the execution of the statements, and update of the variable value, the condition is checked for true or false value. If it is evaluated to true, next iteration of loop starts.
- When the condition becomes false, the loop terminates which marks the end of its life cycle.
- It is important to note that the do-while loop will execute its statements atleast once before any condition is checked, and therefore is an example of exit control loop.
Pitfalls of Loops
- Infinite loop: One of the most common mistakes while implementing any sort of looping is that it may not ever exit, that is the loop runs for infinite time. This happens when the condition fails for some reason. Examples:
- Infinite for loop :
Java
infinite while loop:
Java
Java
Another pitfall is that you might be adding something into you collection object through loop and you can run out of memory. If you try and execute the below program, after some time, out of memory exception will be thrown.
Java
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Unknown Source) at java.util.Arrays.copyOf(Unknown Source) at java.util.ArrayList.grow(Unknown Source) at java.util.ArrayList.ensureCapacityInternal(Unknown Source) at java.util.ArrayList.add(Unknown Source) at article.Integer1.main(Integer1.java:9)
Nested Loop:
Nested loop means a loop statement inside another loop statement.
There are different combinations of loop using for loop, while loop, do-while loop.