Concatenating elements in an array to a string Concatenating elements in an array to a string arrays arrays

Concatenating elements in an array to a string


Use StringBuilder instead of StringBuffer, because it is faster than StringBuffer.

Sample code

String[] strArr = {"1", "2", "3"};StringBuilder strBuilder = new StringBuilder();for (int i = 0; i < strArr.length; i++) {   strBuilder.append(strArr[i]);}String newString = strBuilder.toString();

Here's why this is a better solution to using string concatenation: When you concatenate 2 strings, a new string object is created and character by character copy is performed.
Effectively meaning that the code complexity would be the order of the squared of the size of your array!

(1+2+3+ ... n which is the number of characters copied per iteration).StringBuilder would do the 'copying to a string' only once in this case reducing the complexity to O(n).


Simple answer:

Arrays.toString(arr);


Arrays.toString(arr);

output is [1,2,3] and you storing it to your string . and printing it so you get output [1,2,3].

If you want to get output 123 try this:

public static void main(String[] args) {    String[] arr= {"1","2","3"};    String output ="";    for(String str: arr)        output=output+str;    System.out.println(output);}

Output:

123