About the length of a string literal constant in Java

Source: Internet
Author: User

Although this problem should be difficult to meet, but it will be confused. I do not know if you have encountered the case of writing SQL statements in Java code with strings, but if the length of the SQL statement string is too long, it will be an error. The code is as follows:

Code A

String str = "567890123456789...0123456789";//Because the string length is too long, omit the part, the length is 65535
System.out.println (Str.length ());   Compile an error: Error: (EUR) Java: constant string too long
Code b
String str = "67890123456789...0123456789";//Because the string length is too long, omit the part, the length is 65534
System.out.println (Str.length ());   Compile pass, run result: 65534
Code C
String str = "67890123456789...0123456789";//Because the string length is too long, omit part, length is 65534
str = "5" + str;
System.out.println (Str.length ());   Compile pass, run result: 65535
Inside a string is stored as a char array, and the length of the array is of type int, then the maximum allowable length for string is Integer.max_value = 2^31-1 = 2147483647. And because the characters in Java are stored in 16-bit, it probably takes 4GB of memory to store the maximum length of the string.
But this is only for string variables, if it is string constants, such as "ABC", "1234" and so on in the code of string str, then the maximum allowable length depends on the size of the string in the constant pool, which is the storage format of the string in the class format file:
Constant_utf8_info {
    u1 tag;
    U2 length;
    U1 bytes[length];
}
U2 are unsigned 16-bit integers, so the maximum length of string str theoretically allowed is 2^16-1=65535. However, the actual test indicates that the maximum allowable length is only 65534, exceeding the compile error.
Reprint Address: Http://blog.csdn.net/xyc_csdn/article/details/72582016?locationNum=6&fps=1

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.