Java allows you to assemble String
objects into larger strings by using operators +
or +=
. This is known as string concatenation. When both operands of operator +
are String
objects, operator +
creates a new String
object in which the characters of the right operand are placed at the end of those in the left operand—e.g., the expression "hello " + "there"
creates the String "hello there"
.
In line 24 of Fig. D.2, the expression "Maximum is: " + result
uses operator +
with operands of types String
and double
. Every primitive value and object in Java has a String representation. When one of the +
operator’s operands is a String
, the other is converted to a String
, then the two are concatenated. In line 24, the double
value is converted to its String
representation and placed at the end of the String "Maximum is: "
. If there are any trailing zeros in a double
value, these will be discarded when the number is converted to a String
—for example 9.3500 would be represented as 9.35.
Primitive values used in String
concatenation are converted to String
s. A boolean
concatenated with a String
is converted to the String "true"
or "false"
. All objects have a toString
method that returns a String
representation of the object. When an object is concatenated with a String
, the object’s toString
method is implicitly called to obtain the String
representation of the object. ToString
can be called explicitly.