Java Reference
In-Depth Information
Table 4-2.
(
continued
)
Data Type
Value
String Representation
double
89.12
"89.12"
0.0
"0.0"
-0.0
"-0.0"
Double.POSITIVE_INFINITY
"Infinity"
Double.NEGATIVE_INFINITY
"-Infinity"
Double.NaN
"NaN"
If a
String
variable contains the
null
reference, the concatenation operator uses a string
"null"
. The following
examples illustrate the use of string representations of the values of primitive data types in string concatenation:
boolean b1 = true;
boolean b2 = false;
int num = 365;
double d = -0.0;
char c = 'A';
String str1;
String str2 = null;
str1 = b1 + " friends"; // Assigns "true friends" to str1
str1 = b2 + " identity"; // Assigns "false identity" to str1
// Assigns "null and void" to str1. Because str2 is null, it is replaced
// by a string "null" by the concatenation operator
str1 = str2 + " and void";
str1 = num + " days"; // Assigns "365 days" to str1
str1 = d + " zero"; // Assigns "-0.0 zero" to str1
str1 = Double.NaN + " is absurd"; // Assigns "NaN is absurd" to str1
str1 = c + " is a letter"; // Assigns "A is a letter" to str1
str1 = "This is " + b1; // Assigns "This is true" to str1
// Assigns "Beyond Infinity" to str1
str1 = "Beyond " + Float.POSITIVE_INFINITY
It may be confusing to determine the result of an expression that uses more than one + operator and strings. What
will be the result of the expression
12 + 15 + " men"?
Will the result be
"1215 men"
or
"27 men"?
The key to finding
the correct answer is to find which
+
is an arithmetic operator and which
+
is a string concatenation operator.
If both the operands are numeric, the + operator performs addition. If either operand is a string, the + operator
performs string concatenation. The execution of an expression proceeds from left to right unless overridden by using
parentheses. In the expression
12 + 15 + " men"
, the first + from the left performs addition on
12
and
15
, which
results in
27
. After that, the expression reduces to
27 + " men"
. Now, the + operator performs a string concatenation
because the right-hand operand,
" men"
, is a string and it results in
"27 men"
.