编译期是65535个字符,运行期可以有4G大小容量的字符。
原因:
1、字符串变量声明赋值,进入常量池,必须要遵守常量池规则,JAVA虚拟机规范一文对常量池有规约,常量池用CONSTANT_String_info表示字符串类型的变量值,构造方法参数 u2表示两个字节的无符号数,那么1个字节有8位,2个字节就有16位。
16位无符号数可表示的最大值位2^16 - 1 = 65535。但是规范中说明等于65535时也会抛limit.string过长错误
(The length of field and method names, field and method descriptors, and other constant string values is limited to 65535 characters by the 16-bit unsigned length item of the CONSTANTUtf8info structure (§4.4.7). Note that the limit is on the number of bytes in the encoding and not on the number of encoded characters. UTF-8 encodes some characters using two or three bytes. Thus, strings incorporating multibyte characters are further constrained. )
2、运行时长度不能超过Int的范围,否则会抛异常。