What happens under the hood when bytes converted to String in Java?

后端 未结 4 1913
半阙折子戏
半阙折子戏 2021-01-17 17:57

I have a problem when trying to convert bytes to String in Java, with code like:

byte[] bytes = {1, 2, -3};

byte[] transferred = new String(bytes, Charsets.         


        
4条回答
  •  别那么骄傲
    2021-01-17 18:36

    There is a line in the documentation of the constructor:

    This method always replaces malformed-input and unmappable-character sequences with this charset's default replacement string.

    This is definitely the culprit here, as -3 is invalid in UTF-8. By the way, if you are really interested, you can always download the source of the rt.jar, and debug into it.

提交回复
热议问题