Java Reference
In-Depth Information
Consider the following piece of code:
int num1 = 12;
int num2 = 15;
String str1 = " men";
String str2;
You want to create a string of “1215 men” using the three variables (
num1
,
num2
, and
str1
) and the + operator. You
want to assign the result to
str2
. The following is a first attempt:
str2 = num1 + num2 + str1;
This statement will assign
"27 men"
to
str2
.
Another solution is to place num2 + str1 in parentheses.
str2 = num1 + (num2 + str1); // Assigns "1215 men" to str2
The expression in parentheses is evaluated first. The expression
(num2 + str1)
is evaluated first to reduce the
expression to
num1
+
"15 men"
, which in turn will evaluate to
"1215 men"
.
Another option is to place an empty string in the beginning of the expression.
str2 = "" + num1 + num2 + str1; // Assigns "1215 men" to str1
In this case,
"" + num1
is evaluated first, and it results in
"12"
, which reduces the expression to
"12" + num2 +
str1
. Now
"12" + num2
is evaluated, which results in “1215”. Now the expression is reduced to “1215” +
" men"
, which
results in a string
"1215 men"
.
You may also place an empty string between
num1
and
num2
in the expression to get the same result.
str2 = num1 + "" + num2 + str1; // Assigns "1215 men" to str2
Sometimes the string concatenation is trickier than you think. Consider the following piece of code:
int num = 15;
boolean b = false;
String str1 = “faces";
String str2 = b + num + str1; // A compile-time error
The last line in this snippet of code will generate a compile-time error. What is wrong with the statement? You
were expecting a string of “false15faces” to be assigned to str2, weren't you? Let's analyze the expression b +
num +
str1
. Is the first + operator from left an arithmetic operator or a string concatenation operator? For a + operator to be
a string concatenation operator, it is necessary that at least one of its operands is a string. Since neither
b
nor
num
is a
string, the first + operator from the left in
b + num + str1
is not a string concatenation operator. Is it an arithmetic
addition operator? Its operands are of type
boolean
(
b
) and
int
(
num
). You have learned that an arithmetic addition
operator (+) cannot have a
boolean
operand. The presence of a
boolean
operand in the expression
b + num
caused
the compile-time error. A
boolean
cannot be added to a number. However, the + operator works on a
boolean
as a
string concatenation operator if another operand is a string. To correct the above compile-time error, you can rewrite
the expression in a number of ways, as shown:
str2 = b + (num + str1); // Ok. Assigns "false15faces" to str2
str2 = "" + b + num + str1; // Ok. Assigns "false15faces" to str2
str2 = b + "" + num + str1; // Ok. Assigns "false15faces" to str2