我试图了解编译器如何查看以下打印语句。这很简单但有点有趣。
这会打印附加值。足够有说服力。
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/