Using + to Concatenate Strings

We can use + to concatenate (join) Strings.

What will be printed by the following commands?

    String  a  =  "A" ;
    String  b  =  "BB" ;
    String  c  =  "CCC";
    output( 1 + a + 2 + b + 3 + c );
    output( a + b + c + 1 + 2 + 3 );
    output( a + b + c + (1 + 2) + 3);

Explain why the last two results are different.

Solution

    1A2BB3CCC

    ABBCCC123

    ABBCCC33

    The parentheses force (1+2) to be performed first,
    as normal numeric addition.  The rest perform concatenation,
    because it starts with a+b, which is a String.