java - 使用 add 运算符理解 java 字符串

标签 java string operator-overloading operators

我试图了解编译器如何查看以下打印语句。这很简单但有点有趣。

这会打印附加值。足够有说服力。

System.out.println(1+2); //output: 3

下面的输出看起来也很有说服力:

System.out.println(1+2+"3");//output: 33

我的问题(基于上述行为)在这里。

System.out.println("1"+2+3);//Should be 15 right? NO. It is 123.

我尝试了其他几个类似的语句。我能够看到一两个清晰的行为。

  • 如果整数在前面,没有引号,它们会被添加,随后的整数只是作为后缀附加到从前面添加的值。

  • 如果语句以字符串开头,在引号下,则所有其他后续元素都将作为后缀附加。

这是在 java api 文档中的某个地方吗?或者只是非常明显的字符串或添加我没有看到的运算符行为。我们将不胜感激您的任何宝贵见解。

这是代码片段:

public static void main(String[] args) {
    System.out.println(1+2);
    System.out.println(1+2+"3");
    System.out.println("1"+2+3); 
    System.out.println("1"+2+"3");
    System.out.println("1"+2);
}
//   The Console output:
//      3
//      33
//      123
//      123
//      12

最佳答案

我猜 Java specification最好的解释是:

The + operator is syntactically left-associative, no matter whether it is determined by type analysis to represent string concatenation or numeric addition. In some cases care is required to get the desired result. For example, the expression:

a + b + c

is always regarded as meaning:

(a + b) + c

因此,如果 a 是一个 String,那么它将与 b 连接。结果将是 String 类型,因此它继续与 c 连接。

关于java - 使用 add 运算符理解 java 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29552700/

相关文章:

swift - 如何解决字符串大写问题

java - 我尝试制作 ListView 并从字符串中获取数据,但出现此错误

c++ - 为什么 `<< std::endl` 不调用我希望它调用的运算符(operator)?

c++ - 新建/删除运算符重载和基类

f# - 再次在 F# 中自定义前缀运算符

java - 如何使用 `string.startsWith()` 方法忽略大小写?

java - 能容纳最多内存空间的变量?

java - Json Gson 绑定(bind)不起作用(异常对象/字符串)

Java 连接到数据库

java.lang.String#isEmpty() 与 org.apache.commons.lang.StringUtils#isEmpty()