understanding the java string with add operator

前端 未结 4 1873
轮回少年
轮回少年 2021-01-16 04:04

I am trying to understand how the compiler views the following print statements. It is simple yet a bit intriguing.

This prints the added value. Convincing enough.<

4条回答
  •  星月不相逢
    2021-01-16 04:36

    The + operator is overloaded in the compiler. If both operands are numeric, + is addition. If either or both operands are String, + is string concatenation. (If one operand is String and the other is numeric, the number is cast to a String). Finally, + binds left-to-right.

    All this causes a compound formula a + b + c + ... to do addition left-to-right until it hits the first string operand, at which point it switches to string concatenation for the remainder of the formula. So...

    "1" + 2 + 3 + 4 = 1234   /* cat cat cat */
    1 + "2" + 3 + 4 = 1234   /* cat cat cat */
    1 + 2 + "3" + 4 = 334    /* add cat cat */
    1 + 2 + 3 + "4" = 64     /* add add cat */
    

提交回复
热议问题