Java Reference
In-Depth Information
String concatenation
The plus operator ( + ) has different meanings, depending on the type of its operands. If both
operands are numbers, it represents addition, as we would expect. Thus,
42 + 12
adds those two numbers and the result is 54. However, if the operands are strings, then the
meaning of the plus sign is string concatenation, and the result is a single string that consists of
both operands stuck together. For example, the result of the expression
"Java" + "with BlueJ"
is the single string
"Javawith BlueJ"
Note that the system does not automatically add a space between the strings. If you want a
space, you have to include it yourself within one of the strings.
If one of the operands of a plus operation is a string and the other is not, then the other operand
is automatically converted to a string, and then a string concatenation is performed. Thus,
"answer: " + 42
results in the string
"answer: 42"
This works for all types. Whatever type is “added” to a string is automatically converted to a
string and then concatenated.
Back to our code in the getDisplayValue method. If value contains 3, for example, then the
return "0" + value;
will return the string " 03 " . In the case where the value is greater than 9, we have used a little trick:
return "" + value;
Here, we concatenate value with an empty string. The result is that the value will be converted
to a string and no other characters will be prefixed to it. We are using the plus operator for the
sole purpose of forcing a conversion of the integer value to a value of type String .
Exercise 3.13 Does the getDisplayValue method work correctly in all circumstances?
What assumptions are made within it? What happens if you create a number display with limit
800, for instance?
Exercise 3.14
Is there any difference in the result of writing
return value + "";
rather than
return "" + value;
in the getDisplayValue method?
Search WWH ::

Custom Search