user3437460 user3437460 - 2 months ago 8
Java Question

Order of empty string in string conversion by concatenating empty string

There are several ways to perform a String conversion in Java and some people (including myself) prefers to concatenate an empty string to do the conversion:

Example:

char ch = 'A';
String str = "" + ch; //gets character value and append to str


However the order of the empty String is always a mystery to me. The following will successfully perform a String conversion:

str = ch + "";
str = ch + "" + ch;


but not the following:

str = ch + ch + ""; //if (ch + "") gives us "A", shouldn't this be "65A"?


Que: To be safe, we can always place the empty String infront, but I want to know how Java interprets the concatenation when the (empty) string is placed in other locations (such as in between or at the back).

Answer

The + operator is left-associative, which means that it is grouped from left-to-right.

str = ch + ch + "";

This is equivalent to

str = (ch + ch) + "";
 // = ('A' + 'A') + "";
 // = 130 + "";
 // = "130";

not

str = ch + (ch + "");
 // = 'A' + ('A' + "");
 // = 'A' + "A";
 // = "AA";

char + String and String + char both result in a String. But char + char returns an int. Do you see now why a second + ch doesn't work?