I have a code to concatenate strings. However, for some reason, the final string is not a combination of the required strings. Consider the following code :
//cusEmail is of type String[]
String toList = "";
for(i=0; i < cusEmail.length - 1; i++) {
toList.concat(cusEmail[i]);
toList.concat("; ");
System.out.println(cusEmail[i]);
}
toList.concat(cusEmail[i]);
System.out.println(toList);
The first sout statement displays the strings in cusEmail[i] correctly. However, once concatenated, the second sout displays a blank / empty. Any reason for this? Am i concatenating it correctly?
Stringobjects are immutable. CallingconcatontoListwill not change the value of thetoListobject. Insteadconcatwill return a differentStringobject that is a concatenation of the two strings. For your example, you will want to store the result of each of the calls toconcatin thetoListvariable.For example,
An alternative to using the
concatmethod would be to use the concatenation operator. This might be a little nicer to read.Note, however, that each time one string is concatenated onto another string, a new
Stringobject needs to be created that contains copies of the information in the two original strings. This can be a costly way of building a string when it is done over and over in a loop such as what you have. This is true whether you use theconcatmethod or the concatenation operator. An alternative is to use aStringBuilderobject to build your string.