带有+运算符的Java String Concatenation
我对字符串连接感到困惑。
String s1 = 20 + 30 + "abc" + (10 + 10); String s2 = 20 + 30 + "abc" + 10 + 10; System.out.println(s1); System.out.println(s2);
输出是:
50abc20
50abc1010
我想知道为什么20 + 30在两种情况下都加在一起,但是10 + 10需要括号才能被添加(s1)而不是连接到String(s2)。 请解释String运算符+
如何在这里工作。
加法是左联的。 采取第一种情况
20+30+"abc"+(10+10) ----- ------- 50 +"abc"+ 20 <--- here both operands are integers with the + operator, which is addition --------- "50abc" + 20 <--- + operator on integer and string results in concatenation ------------ "50abc20" <--- + operator on integer and string results in concatenation
在第二种情况:
20+30+"abc"+10+10 ----- 50 +"abc"+10+10 <--- here both operands are integers with the + operator, which is addition --------- "50abc" +10+10 <--- + operator on integer and string results in concatenation ---------- "50abc10" +10 <--- + operator on integer and string results in concatenation ------------ "50abc1010" <--- + operator on integer and string results in concatenation
添加到关联性的概念,您可以确保通过使用括号始终将一个字符串与一个整数配对来确保两个整数永远不会加在一起,这样就可以进行所需的连接操作而不是添加。
String s4 = ((20 + (30 + "abc")) + 10)+10;
会产生:
2030abc1010
另外,为了补充这个话题,Jonathan Schober的答案的错误部分让我想起了一件事:
a+=something
不等于a=a+
: +=
评估右边,然后才将其添加到左侧。 所以它必须重写,它相当于:
a=a+(something); //notice the parentheses!
显示差异
public class StringTest { public static void main(String... args){ String a = ""; a+=10+10+10; String b = ""+10+10+10; System.out.println("First string, with += : " + a); System.out.println("Second string, with simple =\"\" " + b); } }
您需要以空字符串开头。
所以,这可能有效:
String s2 = ""+20+30+"abc"+10+10;
或这个:
String s2 =""; s2 = 20+30+"abc"+10+10; System.out.println(s2);
你需要知道一些规则:
1,Java运算符优先级,大多数是从左到右
2,括号优先于+符号优先。
3,结果为sum,如果+符号的两边都是整数,则为连接。