Giter Club home page Giter Club logo

Comments (3)

bfchengnuo avatar bfchengnuo commented on May 16, 2024

浅层

通过阅读 String 类的源码,知道有这样的成员变量:
private final int count;
其中,注释也说的比较清楚:
count 用来记录字符串的长度,是 int 型,则 String 的最大长度为 Integer.MAX_VALUE,即 2 的 31 次方。

from myrecord.

bfchengnuo avatar bfchengnuo commented on May 16, 2024

深层

《深入理解java虚拟机》中讲到 Class 文件结构。得知在编译为字节码文件后,String 类型的变量的值在常量池中使用 CONSTANT_utf8-info 类型表示,而 CONSTANT_utf8-info 型常量的结构为 u1u2u1 :

CONSTANT_Utf8_info {
      u1 tag;
      u2 length;
      u1 bytes[length];
}

u2 是无符号的 16 位整数,因此理论上允许的 string literal 的最大长度是 2^16-1=65535。
然而实际测试表明,允许的最大长度仅为 65534,超过就编译错误了~~

原因分析:
在 class 文件的规范中, CONSTANT_Utf8_info 表中使用一个 16 位的无符号整数来记录字符串的长度的,最多能表示 65535 个字节,而 java class 文件是使用一种变体 UTF-8 格式来存放字符的,null 值使用两个字节来表示,因此只剩下 65534个字节。
也正是变体 UTF-8 的原因,如果字符串中含有中文等非 ASCII 字符,那么双引号中字符的数量会更少(一个中文字符占用三个字节)。

from myrecord.

bfchengnuo avatar bfchengnuo commented on May 16, 2024

补充

65534 只是在编译阶段的限制,字面量形式一般存储在常量池(如上分析 16 位),运行中时,String 对象的内部字符数组可以通过其它手段拼接成大于65534 长度的字符串。

存在堆中,也不绝对是;但是运行时在本地方法只存储该对象的引用,即 reference 类型,该类型可能是 4 个字节,也可能是 8 个字节。所以理论值是 2^32 或者 2^64 。

所以运行时的字符串长度最多还应该是 Integer.MAX_VALUE ,2^32 也就是 4G。

from myrecord.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.