看String的源碼可以得知,String實際存儲數據的是char value[],數組的長度是int類型,最大值為231-1= 2147483647
所以String最多存儲231-1個字符(注意這里是字符,而不是字節)
但有的同學可能遇到過這樣的報錯:
明明String並沒有超過231-1,那這是為什么呢?
關於String的長度限制,這里要分兩種情況考慮:
當String為常量時
我們知道,String常量會放入字符串常量池,字符串常量池對字符串的長度做了限制
字符串在class格式文件中的存儲格式為:
CONSTANT_Utf8_info {
u1 tag;
u2 length;
u1 bytes[length];
}
u2是無符號的16位整數,最大值為216-1=65535
the class file format spec中也有說明:
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.
所以String在字符串常量池里的限制為65535個字節(注意這里是字節,而不是字符)
字符與字節的關系與編碼有關,這里不討論
當String為變量時
為變量時,則長度限制為231-1= 2147483647個字符。當然塞不塞得下得看你內存了(。・∀・)ノ
如果面試官問你String有沒有長度限制時,你如果從這兩方面答,穩得一匹,還能順便引出JVM的東西,當場錄取😁