Java

For Loop in Java

  • Java
  • 6 mins read

In Java, for loop is a powerful and versatile construct. Starting with JDK 5, there are two kinds of the for loop. First is the conventional(traditional) form that has been in practice since the original version of Java. The second is the newer “for-each” form. Starting with the traditional form, here is the usual form of the traditional for statement:

For Loop in Java

for(initialization; condition; iteration) { 
// body
}

If just one statement is being repeated, there is no need for the curly braces. The for loop operates as follows. When the loop first begins, the initialization portion of the loop is executed. Commonly, this is an expression that sets the value of the loop control variable, which operates as a counter that controls the loop. It is essential to know that the initialization expression is executed only once. Next, the condition is evaluated. This should be a Boolean expression.

It normally tests the loop control variable upon a target value. If this expression is true, then the loop body is executed. If it is false, the loop ends. Next, the iteration part of the loop is executed. This usually is an expression that decrements or increments the variable which controls the loop.

The loop iteration in Java, first evaluating the conditional expression, then executing the loop body, and then executes the body part of the for loop. This process happens until the condition evaluates to false.

Here is a version of the “tick” program that uses a for loop:

// Demonstrate the for loop.
class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);
} 
}

Initialize Loop Control Variables Inside the for Loop

Usually, the variable that controls a for loop is required only for the loop and is not used elsewhere. When this is the case, it is reasonable to declare the variable inside the initialization portion of the for. For instance, here is the other program recorded so that the loop control variable n is declared as an int inside the for:

// Declare a loop control variable inside the for.
class ForTick {
public static void main(String args[]) {
// here, n is declared inside of the for loop
for(int n=10; n>0; n--)
System.out.println("tick " + n);
}
}

When a variable is declared by a you inside a for loop, there is one crucial point to know: the scope of that variable ends when the for statement ends. (i.e, the scope of the variable is restricted to the for loop.) Outside the for loop, the variable will cease to exist. If you want to use the loop control variable elsewhere in your program, you will not be able to declare it inside the for loop.

When the loop control variable is not required elsewhere, most Java programmers declare it inside the for. For instance, here is a simple program that tests for prime numbers. Observe that the loop control variable, i, is declared inside the for as it is not needed elsewhere.

// Test for primes.
class FindPrime {
public static void main(String args[]) {
int num;
boolean isPrime;
num = 14;
if(num < 2) isPrime = false;
else isPrime = true;
for(int i=2; i <= num/i; i++) {
if((num % i) == 0) {
isPrime = false;
break; }
}
if(isPrime) System.out.println("Prime");
else System.out.println("Not Prime");
  }
}

Using the Comma

There will be moments when you will require to add more than one statement in the initialization and iteration portion of the for loop. For instance, consider the loop in the following program:

class Sample {
public static void main(String args[]) {
int a, b;
b = 4;
for(a=1; a<b; a++) {
System.out.println("a = " + a);
System.out.println("b = " + b);
b--;
} }
}

As you can observe, the loop is controlled by the interaction of two variables. Since the loop is directed by two variables, it would be helpful if both could be added in the for statement, itself, instead of b being managed manually. Luckily, Java gives a way to achieve this.

To provide two or more variables to control a for loop, Java allows you to add multiple statements in both the initialization and iteration parts of the for. Each statement is parted from the next with a comma.
Using the comma, the following for loop can be more efficiently coded, as shown here:

// Using the comma.
class Comma {
public static void main(String args[]) {
int a, b;
for(a=1, b=4; a<b; a++, b--) {
System.out.println("a = " + a);
System.out.println("b = " + b);
} }
}

In this example, the initialization part fixes the values of both a and b. The two comma-separated statements in the iteration part are executed every time the loop repeats. The program generates the following output:

a= 1 b= 4 a= 2 b= 3

Note: If you know C/C++, then you know that in those languages the comma is an operator that can be utilized in any logical expression. Nevertheless, this is not the case with Java. In Java, the comma is a separator.

Some for Loop Variations

The for loop provides a number of variations that increase its potential and applicability. Let’s look at some examples.

One of the most obvious variations involves conditional expression. Especially, this expression does not need to test the loop control variable against some target value. In fact, the condition controlling the for can be any Boolean expression. For instance, consider the following fragment:

boolean done = false;
for(int i=1; !done; i++) {
// ...
if(interrupted()) done = true;
}
In this example, the for loop proceeds to run until the boolean variable done is set to true. It does not check the value of i.
The following is an another example:
// Parts of the for loop can be empty.
class ForVar {
public static void main(String args[]) {
int i;
boolean done = false;
i = 0;
for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10) done = true;
i++;
} }
}

Here, the initialization and iteration expressions have been driven out of the for. Thus, parts of the for are null.

Here is one more for loop variation. You can purposely create an infinite loop (a loop that never ends) if you leave all three parts of the for empty. For example:

for( ; ; ) {
// ...
}

This loop will run forever as there is no condition under which it will terminate.

See also:

Reference: