Difference between String.length() and String.getBytes().length

前端 未结 4 771
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 19:30

I am beginner and self-learning in Java programming. So, I want to know about difference between String.length() and String.getBytes().length in Ja

4条回答
  •  时光取名叫无心
    2020-12-08 20:15

    In short, String.length() returns the number of characters in the string while String.getBytes().length returns the number of bytes to represent the characters in the string with specified encoding.

    In many cases, String.length() will have the same value as String.getBytes().length. But in cases like encoding UTF-8 and the character has value over 127, String.length() will not be the same as String.getBytes().length. Here is an example which explains how characters in string is converted to bytes when calling String.getBytes(). This should give you a sense of the difference between String.length() and String.getBytes().length.

提交回复
热议问题