Explain For Loop In Java Programming, Program For For Loop In Java With Explanations
In This Topic & Blog Having Any Query Then Post your Comment and Suggestion Below

The For Loop In Java
As you may know from your previous programming experience, loop statements are an
important part of nearly any programming language. Java is no exception. In fact, as you
will see in Chapter 5, Java supplies a powerful assortment of loop constructs. Perhaps the
most versatile is the
for
loop. The simplest form of the
for
loop is shown here:
for( initialization; condition; iteration ) statement ;
In its most common form, the initialization portion of the loop sets a loop control variable
to an initial value. The condition is a Boolean expression that tests the loop control variable.
If the outcome of that test is true, the
for
loop continues to iterate. If it is false, the loop
terminates. The iteration expression determines how the loop control variable is changed
each time the loop iterates. Here is a short program that illustrates the
for
loop:
/*
Demonstrate the for loop.
Call this file "ForTest.java".
*/
class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is x: " + x);
}
}
This program generates the following output:
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
This is x: 5
This is x: 6
This is x: 7
This is x: 8
This is x: 9
In this example,
x
is the loop control variable. It is initialized to zero in the initialization portion
of the
for
. At the start of each iteration (including the first one), the conditional test
x < 10
is
performed. If the outcome of this test is true, the
println( )
statement is executed, and then
the iteration portion of the loop is executed. This process continues until the conditional test
is false.
As a point of interest, in professionally written Java programs you will almost never see
the iteration portion of the loop written as shown in the preceding program. That is, you will
seldom see statements like this:
x = x + 1;
The reason is that Java includes a special increment operator which performs this operation
more efficiently. The increment operator is
++
.
(That is, two plus signs back to back.) The
increment operator increases its operand by one. By use of the increment operator, the
preceding statement can be written like this:
x++;
Thus, the
for
in the preceding program will usually be written like this:
28
for(x = 0; x<10; x++)
You might want to try this. As you will see, the loop still runs exactly the same as it did
before.
Java also provides a decrement operator, which is specified as
––
.
This operator decreases
its operand by one.
Labels: Java - J2SE