带有+运算符的Java String Concatenation [英] Java String Concatenation with + operator

查看:595
本文介绍了带有+运算符的Java String Concatenation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对字符串连接感到困惑。

I got confused with the String concatenation.

String s1 = 20 + 30 + "abc" + (10 + 10);
String s2 = 20 + 30 + "abc" + 10 + 10;
System.out.println(s1);
System.out.println(s2);

输出为:


50abc20

50abc1010

50abc20
50abc1010

我想知道为什么 20 + 30 在两种情况下都加在一起,但 10 + 10 需要括号才能添加(s1)而不是连接到字符串(s2)。请解释String运算符 + 如何在这里工作。

I wonder why 20 + 30 are added together in both cases, but 10 + 10 require parenthese in order to be added (s1) instead of concatenated to the String (s2). Please explain how the String operator + works here.

推荐答案

添加是左联想。第一种情况

Addition is left associative. Taking the first case

20+30+"abc"+(10+10)
-----       -------
  50 +"abc"+  20    <--- here both operands are integers with the + operator, which is addition
  ---------
  "50abc"  +  20    <--- + operator on integer and string results in concatenation
    ------------
      "50abc20"     <--- + operator on integer and string results in concatenation

在第二种情况下:

20+30+"abc"+10+10
-----
  50 +"abc"+10+10  <--- here both operands are integers with the + operator, which is addition
  ---------
   "50abc"  +10+10  <--- + operator on integer and string results in concatenation
    ----------
    "50abc10"  +10  <--- + operator on integer and string results in concatenation
     ------------
      "50abc1010"   <--- + operator on integer and string results in concatenation

这篇关于带有+运算符的Java String Concatenation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆