Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does String(byte[]) create a deep copy of the byte array?

Or is it that it just gets a reference to it?

I have a byte array that gets re-written by an external library - is it safe to pass it into a String constructor, or should I create a clone first?

byte[] b = MagicLib.getData();
String s = new String(b);

// actually a pointer to previous memory, just with different data
b = MagicLib.getMoreData(); 
like image 775
Sam Avatar asked Jun 12 '26 17:06

Sam


1 Answers

A String contains an array of chars, not bytes. Therefore, the String cannot share the byte's storage.

Additionally, note that the byte[] will be decoded into characters according to the platform default charset (per the documentation on String(byte[])), which implies further that a decoded version of the byte[] array has to be separately constructed.

like image 154
nneonneo Avatar answered Jun 14 '26 07:06

nneonneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!