看String的源码:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
{
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
String内部是以char数组的形式存储,数组的长度是int类型,那么String允许的最大长度就是Integer.MAX_VALUE了,即为 2^31 - 1 = 2147483647。又由于java中的字符是以16位存储的,因此大概需要4GB的内存才能存储最大长度的字符串。不过这仅仅是对字符串变量而言,如果是字符串字面量(string literals),如“abc"、"1a2b"之类写在代码中的字符串literals,那么允许的最大长度取决于字符串在常量池中的存储大小,也就是字符串在class格式文件中的存储格式:
CONSTANT_Utf8_info {
u1 tag;
u2 length;
u1 bytes[length];
}
u2是无符号的16位整数,因此理论上允许的string literal的最大长度是2^16-1=65535。然而实际测试表明,允许的最大长度仅为65534,超过就编译错误了,有兴趣可以写段代码试试,估计是length还不能为0。
代码1:
String s1="1111......111"; //省略部分内容,长度是65535
System.out.println(s1.length()); //编译报错
代码2:
String s2="222......222"; //省略部分内容,长度是65534
System.out.println(s2.length()); //编译通过,控制台打印655534
代码3:
String s3="333......333"; //省略部分内容,长度是65534
s3="3"+s3;
System.out.println(s3.length()); //编译通过,控制台打印655535
参考:http://www.blogjava.net/killme2008/archive/2009/01/15/251368.html