can we add String array into StringBuffer or StringBuilder in java?

Nithya picture Nithya · Oct 7, 2014 · Viewed 9k times · Source

Now I am developing a simple project on Java.In that I include String Builder to append and print strings on console.When I am trying to append string array into string Builder,it prints object instead of array of strings on console.any one please tell whether my try is right or wrong.

Answer

Mena picture Mena · Oct 7, 2014
  • Add Arrays.toString(yourArray) if you want to add the representation of your String array.
  • If it's a multiple-dimension array (e.g. a String[][]), then add Arrays.deepToString(yourArray) to your StringBuilder.
  • Adding the array itself will add the default String representation.
  • Finally, if you need control over how you represent your array to String, you'll need to iterate the elements yourself and add them to the StringBuilder in a customized format.

Edit

As a side-note, to make this work with arrays of custom Objects, you'll probably want to override the Object.toString method, otherwise your elements will be printed with the default String representation of Object (i.e. this).