0

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.

2 Answers 2

1

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"));
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

could you show me an example string after it is converted to byte array? I need to see its contents to understand

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.