Strictly speaking, String does have a length limit.
1. String internally uses a char[] array to store the content of the string. The array subscript is an integer (you can also refer to the String construction method String(char value[], int offset, int count) to know The number of characters is represented by an integer), and the range of the integer (Java specifies 32 bits) is 2G. That is to say, the maximum length of a Java array is 2G, that is, the string cannot exceed 2G characters.
2. Are there any other restrictions on the array size of Java? In fact, the size of the array cannot exceed the size of the Java heap, and the maximum size of the Java heap can be specified through startup parameters. If the Java heap is large enough, the maximum length of the array can continue to increase.
So, according to theory, the number of characters in a string cannot exceed 2G, but it is possible to have less than 2G characters.
String is stored internally in the form of a char array. The length of the array is int type, so the maximum length allowed by String is Integer.MAX_VALUE. And since characters in Java are stored in 16 bits, approximately 4GB of memory is needed to store the maximum length of the string. But this is only for string variables. If it is a string literal (string literals), such as "abc", "1a2b" and other string literals written in the code, then the maximum allowed length depends on the string The storage size in the constant pool, that is, the storage format of strings in class format files:
CONSTANT_Utf8_info {
u1 tag;
u2 length;
u1 bytes[length];
}
u2 is an unsigned 16-bit integer, so the theoretical maximum length of a string literal allowed is 2^16-1=65535. However, after actual testing, it was found that the maximum allowed length is only 65534, and exceeding this limit will cause compilation errors.
The above is the detailed content of Is there any limit on the length of String type in Java?. For more information, please follow other related articles on the PHP Chinese website!