How is string concatenation working here?

tra*_*boo 0 java string string-concatenation

How does string concatenation work here? As the return value is of type String here, so everything should be converted to string. But why is it printing "30Good3040morning" here, instead of "1020Good3040morning". Please Help.

class StringConcatinationWorking{
    public static void main(String ...args){
        String s1 = 10 + 20 + "Good" + 30 + 40 + "morning";
        System.out.println(s1);
    }
}
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 6

请记住,+运算符是左关联的,因此它从左到右“放入括号”。仅当至少一个操作数为a时才执行字符串连接String

请注意,诸如1030不是Strings之类的东西。它们是int文字。

放在方括号后的表达式变为:

(((((10 + 20) + "Good") + 30) + 40) + "morning")
Run Code Online (Sandbox Code Playgroud)

如果我们从最里面的括号开始逐步进行评估,则会得到:

((((30 + "Good") + 30) + 40) + "morning") // 10 + 20
((("30Good" + 30) + 40) + "morning") // 30 + "Good"
(("30Good30" + 40) + "morning") // "30Good" + 30
("30Good3040" + "morning") // "30Good30" + 40
"30Good3040morning" // "30Good3040" + "morning"
Run Code Online (Sandbox Code Playgroud)

注意我们如何得到的子表达式10 + 20,而不是的子表达式30 + 40

为了获得预期的结果,只需在该""术语之前或之后添加一个10术语,这样方括号将变为:

((((((10 + "") + 20) + "Good") + 30) + 40) + "morning")
Run Code Online (Sandbox Code Playgroud)