Java String Concatenation with + operator

java, string

Solution

`+` can represent addition or concatenation.

- If both operands are numeric it is addition.

- If at least one operand is String it is concatenation.

Also addition and concatenation is left associative, so `a+b+c` is same as `(a+b)+c` (the `b` is associated with left `+`).

Taking the first case

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

In the second case:

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

Problem

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); ``` The output is: 50abc20 50abc1010 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.

Original source

Related problems