

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

Can someone please explain me what happens to a String when it's converted to a byte array? what happens to it and how could I add more String to this byte array??

For example: Rockets are fun.

share|improve this question

I think the prior posts covered well what happens to a String in terms of 16 bit -vs- 8 bit representation. The second half of your question, on growing a byte array, is usually performed using System.arraycopy(src, srcPos, dest, destPos, length).

String str="Rockets are fun.";
byte[] ba=str.getBytes();
byte[] bigger=new byte[23];
System.arraycopy(ba, 0, bigger, 0, ba.length);
byte[] toFly=" to fly.".getBytes();
System.arraycopy(toFly, 0, bigger, 15, toFly.length);
System.out.println(new String(bigger, "UTF-8"));
share|improve this answer

When a string is converted to a byte array it simply takes each character (usually 1 byte) and converts it to it's ASCII text value by a simple cast (or other encoding which may mean 2 bytes per character but I'll stick to the simple ASCII example). You can't actually add anything to that array because arrays are sized once and to resize you have to copy that array into a larger array and insert there instead. If you want to do concatenation of strings just stick to the += and + operators for strings which do this for you or StringBuilder(or StringBuffer I forget which it is in Java) in case you need to do a lot of appending since each append creates new immutable strings which is quite costly if done a lot.

share|improve this answer
could you show me an example string after it is converted to byte array? I need to see its contents to understand – Ignacio Pochart Nov 16 '11 at 5:44

Your Answer


