Can anyone tell me the difference and why ???????? I have an example:
int a = 2;
int b = 7;
System.out.println(a+b);
System.out.println(a+b+"String");
System.out.println("String"+a+b+"String");
System.out.println(a+b+"String"+a+b+"String");
System.out.println("String"+a+b+"String"+a+b);
output
9
9String
String27String
9String27String
String27String27
To understand what's going on, consider that these expressions in Java are left-associative. The result of adding int
+ int
is the arithmetic sum of the two values. The result of adding an int
with a String
is equivalent to converting the int
to its String
representation and then performing the +
operation between the two String
s, which concatenates the two values. Thus,
a+b+"String"` => (a + b) + "String"
=> (2 + 7) + "String"
=> 9 + "String"
=> "9String"
a+b+"String"+a+b+"String"` => ((((a + b) + "String") + a) + b) + "String"
=> ((((2 + 7) + "String") + 2) + 7) + "String"
=> (((9 + "String") + 2) + 7) + "String"
=> (("9String" + 2) + 7) + "String"
=> ("9String2" + 7) + "String"
=> "9String27" + "String"
=> "9String27String"
Procedure to determine whether +
means addition or concatenation:
Apply standard operator precedence rules to the expression to work out the order in which the operators are applied.
Examine each +
. If both left and right operand expressions of +
are primitive or wrapped numeric, then the +
is an addition. Otherwise it is string concatenation.
Example:
Applying precedence rules to
a+b+"String"+a+b+"String"
means that it is equivalent to
((((a+b)+"String")+a)+b)+"String"
Then:
a+b
is addition (a+b)+"String")
is concatenation ((a+b)+"String")+a
is concatenation (((a+b)+"String")+a)+b
is concatenation ((((a+b)+"String")+a)+b)+"String"
is concatenation This matches up with the output 9String27String
that you got for that case.
The code
System.out.println("String"+a+b+"String");
is assuming that you want to do String
concatenation.
You could do
System.out.println("String"+(a+b)+"String");
or
System.out.printf("String%dString%n", a+b);
In Java, the plus sign can be used to perform arithmetic addition.
It can also be used to concatenate strings. When the plus sign is used in this manner, the operand on the right is automatically converted to a character string before being concatenated with the operand on the left.
You had better check the String Concatenation Operator + from java specification, you will see the instructions like below,which will give you the answer
请先理解字符串中“+”的含义
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.