Java Reference
In-Depth Information
Catenation is often used in annotating output values to make them more
understandable. Suppose we have two int variables, month and day . Here is a
single statement that prints their values, but annotated with text so that the user
knows what the values are:
Activity 5-3.4
shows execu-
tion of this
statement.
System.out.println(" month " + month + ",\nday " + day);
Note that the new-line character causes the characters following it to be printed
on a separate line.
When using the Java console for output when debugging programs, get in
the habit of annotating the output, even in a minimal fashion, to help you deci-
pher the output.
What is the value of the following expression?
2+5+" apples".
There are two possible values, depending on which operation + is done first:
"7 apples"
"25 apples"
Since + is left associative, the operations are carried out from left to right, so the
first answer is correct. To get the second one, use either of these two expressions,
with the first being preferred because it requires fewer operations:
2 + (5 + " apples")
""+2+5+" apples"
Invocation of function toString
Above, we said that if one operand of + is a String and the other is a prim-
itive-type value, the primitive-type value is converted to a String and catenation
is performed. There is one more case to consider:
c+s
where c contains the name of a folder and s is a String . In this case, the func-
tion call c.toString() is automatically invoked to produce a String represen-
tation of folder c , which is then catenated to s .
Recall that function toString has this specification:
/** = a description of this folder */
public String toString()
For reasons given in Sec. 4.3.1, function toString is present in every folder.
However, it may not do what you want, and that is a good reason to redefine
function toString in every class that you write.
The length of a String
Above, we made a mistake when we drew folders of class String : we omit-
Search WWH ::




Custom Search