众所周知
Java '+' 运算符用于两者
当我同时使用两者时,需要确切地知道预期的行为和应用的规则
当我尝试遵循 Java 代码时
System.out.println("3" + 3 + 3); // print 333 String concatenation ONLY
System.out.println(3 + "3" + 3); // print 333 String concatenation OLNY
System.out.println(3 + 3 + "3"); // print 63 Arithmetic Add & String concatenation
这是基本的运算符优先级,结合 String
连接与数字加法。
引用:
If only one operand expression is of type String, then string
conversion (§5.1.11) is performed on the other operand to produce a
string at run time.
The result of string concatenation is a reference to a String object
that is the concatenation of the two operand strings. The characters
of the left-hand operand precede the characters of the right-hand
operand in the newly created string.
The String object is newly created (§12.5) unless the expression is a
constant expression (§15.28).
An implementation may choose to perform conversion and concatenation
in one step to avoid creating and then discarding an intermediate
String object. To increase the performance of repeated string
concatenation, a Java compiler may use the StringBuffer class or a
similar technique to reduce the number of intermediate String objects
that are created by evaluation of an expression.
For primitive types, an implementation may also optimize away the
creation of a wrapper object by converting directly from a primitive
type to a string.
参见语言规范 here .
长话短说
+
的运算符优先级从左到右
- 如果二元运算中的任何操作数是
String
,则结果是String
- 如果两个操作数都是数字,则结果是一个数字