Java Beginners - Java For Beginners Java For Loop Rating: 5.0/5 (1 vote cast) | Level : Beginners Author : Arunkumar S Download Source : Not Avaliable
Loops with the for Statement - Java for KeywordAs we saw in Repetition with while and do-while there are three looping constructs in java : while, do-while, and for. while is the most straightforward and, in fact, all looping scenarios can be handled with while. for, on the other hand, provides a compact syntax for looping over a range of values--most often over arrays and collections. Before we look at examples of for, let's look at its general form: for(initialization; termination; increment) { statements_to_execute }
This general form shows the format of a for loop and its four parts. The first part of the for construct to execute is the initialization statement. It only executes once, at the beginning of the loop, and allows for the declaration and initialization of variables that will be scoped to the for loop. Most often, this is where you set up int counters used to keep track of which iteration the loop is currently on. The next part of the loop to execute is the termination statement. This is a conditional expression that should eventually resolve to false. the termination statement is evaluated at the beginning of each iteration of the loop. If it evaluates to true, the loop continues and executes the statements_to_execute. If the expression evaluates to false, the loop ends. If the expression never evaluates to false, the loop will continue indefinitely. Each time the termination statement evaluates to true, the statements_to_execute are executed. statements_to_execute can be zero or more statements. Most often, these statements are used to access the next element in an array or collection and then process the element. Finally, the increment statement is executed at the end of each iteration. Most commonly, it will increment the counter variables that were initialized in the initialization statement. The action in the increment statement should move the loop closer to termination. This will eventually end the for loop when the termination_statement finally evaluates to false. Lets look at one of the simplest examples of for: for(int i = 0; i < 10; i++) { System.out.println(i); }
- In this example, the for loop first initializes the variable i to 0. Counters in Java are almost always initialized to 0 because Java arrays and collections are zero-based. This means the first element in an array or collection is element index 0.
- Next, the for loop tests whether 0 is less than 10.
- Since the termination statement (i < 10) evaluated to true, the statements in the curly braces are executed. In this case i is printed to standard out.
- Finally, the first iteration of the loop is completed when the increment statement adds 1 to i (i++).
- Now, the next loop begins by testing the termination statement. After 10 iterations, the termination statement will evaluate to false and the for loop will end.
Output: c:\>arun\javac ForDemo.java c:\>arun\java ForDemo 0 1 2 3 4 5 6 7 8 9
Iterating Over Arrays and Collections
import java.util.ArrayList; import java.util.Iterator;
/** * Demonstrates Java for loop */ public class ForDemo {
public static void main(String args[]) {
System.out.println("\nExample 1"); int dailyRevenue[] = {100, 150, 300, 175, 35, 80, 200}; for(int i = 0, total = 0; i < dailyRevenue.length; i++ ) { total += dailyRevenue[i]; System.out.println("total revenue: " + total); }
System.out.println("\nExample 2"); ArrayList employees = new ArrayList(); employees.add("arun"); employees.add("Justin"); employees.add("Purush"); for(Iterator iter = employees.iterator(); iter.hasNext();) { String e = (String)iter.next(); System.out.println(e); } } }
In ForDemo's example 1, an int array named dailyRevenue is first declared and populated. Then the for loop iterates through the array, adding each dailyRevenue value to total. In this for loop, notice there are two variables declared in the initialization statement, i and total. In the termination statement, the counter variable i is tested against the length of the dailyRevenue array. Finally, after the statements in the curly braces are executed, i is incremented by 1. This will eventually cause i to equal the length of dailyRevenue, ending the loop. In ForDemo's example 2, an ArrayList is declared and populated instead of an array. Example 2 could have used any class that implements the java.util.Collection interface. When using a for loop to iterate over a Collection, there is no counter variable. Instead a java.util.Iterator is created and Iterator.hasNext() is used in the termination statement. When Iterator.hasNext() returns false, the loop ends. Finally, the for's increment statement is not needed, so remains empty. To execute this program, first cut and paste it into a file named ForDemo.java. Save the file to a directory, for instance C:\src. In a DOS or shell window, change directory to the directory containing ForDemo.java. Compile and run it with the javac and java commands, respectively. To review compiling and executing Java classes, see First Java Program - HelloWorld. ForDemo's output: c:\>arun\javac ForDemo.java c:\>arun\java ForDemo Example 1 total revenue: 100 total revenue: 250 total revenue: 550 total revenue: 725 total revenue: 760 total revenue: 840 total revenue: 1040
Example 2 Arun Justin Purush
1 |
Discussion about this tutorial
 Start a new Discussion | Read All Discussion
|