Java Reference
In-Depth Information
When you concatenate a string and an object like
String str = "Hello" + new Point(10, 20);
Java calls the
toString()
method on the
Point
object and concatenate the returned value to the
"Hello"
string.
The above statement will assign a
"Hello(10, 20)"
string to the
str
variable. The above statement is the same as the
following one:
String str = "Hello" + new Point(10, 20).toString();
You use the string concatenation operator (+) to concatenate data of different types. First, Java gets the string
representations of all data before concatenating them. Calling the
toString()
method of an object automatically for
you in a concatenation expression helps you save some typing. If the object reference that is used in concatenation is a
null
reference, Java uses a
"null"
string as the string representation.
The following snippet of code makes the call to the
toString()
method on object references clear. You may
observe that the result is the same when you use the object's reference by itself or you call its
toString()
method in
a string concatenation expression. Similarly, when you use
System.out.println(pt)
, Java automatically calls the
toString()
method on the
pt
reference variable.
Point pt = new Point(10, 12);
String str1 = "Test " + pt;
String str2 = "Test " + pt.toString();
// str1 and str 2 will have the same content
System.out.println(pt);
System.out.println(pt.toString());
System.out.println(str1);
System.out.println(str2);
(10, 12)
(10, 12)
Test (10, 12)
Test (10, 12)
The following snippet of code shows the effect of using a
null
reference in a string concatenation expression
and in the
System.out.println()
method call. Note that you cannot use
pt.toString()
when pt is holding a
null
reference. The call to any method on a
null
reference will generate a runtime exception.
// Set pt to null
Point pt = null;
String str3 = "Test " + pt;
System.out.println(pt);
System.out.println(str3);
//System.out.println(pt.toString()); /* Will generate a runtime exception */
null
Test null