Java Reference
In-Depth Information
The code to print the
3x3
matrix can be written as
// Outer for-loop statement
for(int i = 1; i <= 3; i++) {
// Inner for-loop statement
for(int j = 1; j <= 3; j++) {
System.out.print(i + "" + j);
// Prints a tab after each column value
System.out.print("\t");
}
System.out.println(); // Prints a new line
}
The above piece of code can be explained using the following steps.
The execution starts in the initialization part
(int i = 1)
of the outer
for
-loop statement
where
i
is initialized to 1.
1.
The condition-expression for the outer
for
-loop statement (
i <= 3)
is evaluated for
i
equal to 1, which is true.
2.
The statement part of the outer
for
loop starts with an inner
for
-loop statement.
3.
Now
j
is initialized to 1.
4.
The condition-expression for the inner
for
-loop statement (
j <= 3)
is evaluated for
j
equal to 1, which is true.
5.
The block statement associated with the inner
for
-loop statement is executed, which
prints 11 and a tab.
6.
The expression-list of the inner
for
-loop statement (
j++
) is executed, which increments
the value of
j
to 2.
7.
The condition expression for the inner
for
-loop statement (
j <= 3)
is evaluated for
j
equal to 2, which is true.
8.
The block statement associated with the inner
for
-loop statement is executed, which
prints 12 and a tab. At this stage the printed text is
11 12
9.
The expression-list of the inner
for
-loop statement (
j++
) is executed, which increments
the value of
j
to 3.
10.
The condition-expression for the inner
for
-loop statement (
j <= 3)
is evaluated for
j
equal to 3, which is
true
.
11.
The block statement associated with the inner
for
-loop statement is executed, which
prints 13 and a tab. At this stage the printed text is
11 12 13
12.
The expression-list of the inner
for
-loop statement (
j++
) is executed, which increments
the value of
j
to 4.
13.