算术加法和字符串连接之间的Java '+'运算符?

标签 java string concatenation add

<分区>

众所周知
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
  • 如果两个操作数都是数字,则结果是一个数字

关于算术加法和字符串连接之间的Java '+'运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38352779/

相关文章:

java - 无法从 HTTPS URL 获取 Inputsream - 连接超时 (ConnectException)

java - 如何在没有互联网连接的情况下获取网络提供的日期和时间?

string - 如何找到至少重复一次的字符串中的最大序列?

javascript - JavaScript 中是否可以通过连接两个字符串来调用变量?

r - 如何在R中连接两个数组

java - 将 java.io.File 子类化是一个坏主意吗?

java - 使用配置播种 Dagger 2 Factory

c - 从像 folder1/file1.txt 这样的字符串中提取 C

python - 当使用 **kwargs 语法从 2 个不同的字典形成单个字典对象时,试图理解模糊的行为

c++ - 无法打开存储在字符串 C++ 中的文件名