Difference between two String constructors

I'm wondering the difference between the following 2 statements:

    String str = new String(new char[]{'a', 'b'}); 

and

    String str = new String(new byte[]{'a', 'b'}); 

I get the same thing in the outcome. The only difference i can think of is that i don't have to convert the array type to byte[] when i have a char[] and vice versa.

TIA.

Jon Skeet
people
quotationmark

The difference is that the first is just taking a character array and creating a string of the same length, with the same char contents. The second is decoding from bytes to chars - using the platform default encoding in this case. You can specify the encoding with another constructor argument, and indeed you should almost always do so. (It's very rarely a good idea to use the platform default encoding - and when you want to do so, it's clearer if you do so explicitly.)

For the values of 'a' and 'b' it's unlikely that there'll be a difference in results - although the platform default encoding could be EBCDIC or something else similarly non-ASCII-compatible. But it's worth understanding that fundamentally these are two different operations.

It's a little bit like constructing an image, where the first form would be passing in an array of a mythical PixelColor type, whereas the second form would be more like saying "load it from this PNG file".

people

See more on this question at Stackoverflow