Maximum length of Java string

Source: Internet
Author: User

For portability in CPP, the length of the string is String::size_type, and suddenly you want to know what the maximum string length is allowed in Java. Look at the source of string:

Public final class String
Implements Java.io.Serializable, Comparable<string>, charsequence
111 {
The/** the value is used for character storage. */
113 Private Final char value[];
114
/** The offset is the first index of the storage so is used. */
The private final int offset;
117
118/** The Count is the number of characters in the String. */
119 private Final int count;

String inside is stored as a char array, the length of the array is of type int, then the maximum length allowed by the string is Integer.max_value. And since the characters in Java are stored in 16 bits, it takes approximately 4GB of memory 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 the like, such as the string literals written in code, then the maximum allowable length depends on the size of the string in the constant pool storage, This is the format in which the string is stored in the class format file:

Constant_utf8_info {
U1 tag;
U2 length;
U1 Bytes[length];
}


U2 is an unsigned 16-bit integer, so the maximum length of the theoretically allowable string literal is 2^16-1=65535. However, the actual test shows that the maximum allowed length is only 65534, more than the compilation error, interested in writing a section code to try, it is estimated that the length can not be 0.

Maximum length of Java string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.