Understanding Java String Length Limits and JVM Constant‑Pool Restrictions
This article explains how Java strings are stored, the theoretical 2^31‑1 character limit imposed by the underlying char[] array, and the practical 65534‑character limit enforced by the JVM constant‑pool specification, illustrated with code examples and a small experiment.
Java strings are backed by a char[] array, so their theoretical maximum length is bounded by the maximum size of an int‑indexed array (2^31‑1, about 2 GB of characters).
The String.length() method returns an int, and the Integer class shows that the maximum int value is 2^31‑1, confirming the theoretical limit.
However, when a string literal is compiled, the JVM stores it in the class file constant pool, where the CONSTANT_String entry uses a u2 index. A u2 can represent values from 0 to 65535, and one byte is needed for the terminating instruction, so the effective compile‑time limit is 65534 characters.
int[] arr1 = new int[10]; // 定义一个长度为10的数组<br/>int[] arr2 = {1,2,3,4,5}; // 那么此时数组的长度为5<br/>The article shows an experiment that builds a string of exactly 65534 characters via a loop, prints its length, and assigns it to a literal; the compilation succeeds, confirming the constant‑pool limit.
In summary, at runtime a Java String can hold up to about 2 GB of characters (limited by the int index), but when defined as a literal the JVM restricts it to 65534 characters because of the constant‑pool u2 index.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
