Java Reference
In-Depth Information
Alternatively, you can include an
if
statement inside the loop (the double-test
approach):
public static void multiprint(String s, int times) {
System.out.print("[");
for (int i = 1; i <= times; i++) {
System.out.print(s);
if (i < times) {
System.out.print(", ");
}
}
System.out.println("]");
}
Although the preceding version of the code performs a similar test twice on each
iteration, it is simpler than using the classic fencepost solution and its special case.
Neither solution is better than the other, as there is a tradeoff involved. If you think
that the code will be executed often and that the loop will iterate many times, you
might be more inclined to use the efficient solution. Otherwise, you might choose the
simpler code.
George Boole was such a good logician that Java has a data type named after him.
The Java type
boolean
is used to describe logical true/false relationships. Recall that
boolean
is one of the primitive types, like
int
,
double
, and
char
.
Novices often wonder why computer scientists are so interested in logic. The
answer is that logic is fundamental to computing in the same way that physics is
fundamental to engineering. Engineers study physics because they want to build
real-world artifacts that are governed by the laws of physics. If you don't under-
stand physics, you're likely to build a bridge that will collapse. Computer scien-
tists build artifacts as well, but in a virtual world that is governed by the laws of
logic. If you don't understand logic, you're likely to build computer programs that
collapse.
Without realizing it, you have already used
booleans
. All of the control structures
we have looked at—
if/else
statements,
for
loops, and
while
loops—are con-
trolled by expressions that specify tests. For example, the expression
number % 2 == 0
is a test for divisibility by 2. It is also a Boolean expression. Boolean expressions are
meant to capture the concepts of truth and falsity, so it is not surprising that the
Search WWH ::
Custom Search