Java Reference
In-Depth Information
String i = "Buy seventeen copies of Effective Java!";
The
int
value
0
is converted to the
String
value
"0"
and appended to the blatant plug. The
resulting string is not equal to the original as computed by the
equals
method, so it certainly can't
be identical, as computed by the
==
operator. Therefore, the
boolean
expression (
i != i + 0
)
evaluates to
TRue
and the loop never terminates.
In summary,
operator overloading can be very misleading
. The plus sign in the puzzle looks like
addition, but it is made to perform string concatenation by choosing the correct type for the variable
i
, which is
String
. The puzzle is made even more misleading because the variable is named
i
, a
name that is usually reserved for integer variables.
Good variable, method, and class names are at
least as important to program readability as good comments.
The lesson for language designers is the same as in
Puzzles 11
and
13
. Operator overloading can be
confusing. Perhaps the
+
operator should not have been overloaded for string concatenation. It may
well be worth providing a string concatenation operator, but it doesn't have to be
+
.
< Day Day Up >
Search WWH ::
Custom Search