Java Reference
In-Depth Information
This code prints all of its output on a single line of output. Let's look at some code
that includes a combination of
print
and
println
to produce several lines of output:
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print("*");
}
System.out.println();
}
When you write code that involves nested loops, you have to be careful to indent
the code correctly to make the structure clear. At the outermost level, the preceding
code is a simple
for
loop that executes six times:
for (int i = 1; i <= 6; i++) {
...
}
We use indentation for the statements inside this
for
loop to make it clear that
they are the body of this loop. Inside, we find two statements: another
for
loop and a
println
. Let's look at the inner
for
loop:
for (int j = 1; j <= 10; j++) {
System.out.print("*");
}
This loop is controlled by the outer
for
loop, which is why it is indented, but it itself
controls a statement (the
print
statement), so we end up with another level of indenta-
tion. The indentation thus indicates that the
print
statement is controlled by the inner
for
loop, which in turn is controlled by the outer
for
loop. So what does this inner
loop do? It prints 10 stars on the current line of output. They all appear on the same line
because we are using a
print
instead of a
println
. Notice that after this loop we per-
form a
println
:
System.out.println();
The net effect of the
for
loop followed by the
println
is that we get a line of output
with 10 stars on it. But remember that these statements are contained in an outer loop
that executes six times, so we end up getting six lines of output, each with 10 stars:
**********
**********
**********
**********
**********
**********
Search WWH ::
Custom Search