Why Does Java’s String Have a Length Limit? Uncovering JVM Constraints
This article explains Java's String length limits, detailing how the underlying char[] array, int return type, and JVM constant‑pool specifications together define both the theoretical 2^31‑1 character maximum and the compile‑time literal limit of 65,534 characters.
Preface
In Java, the String class has a length limit, which many developers encounter during interviews or when storing large data such as Base64‑encoded files.
String
String stores characters in a char[] array, so its length is ultimately bounded by the maximum size of an array.
The length() method returns an int, and the maximum value of an int (2^31‑1) implies a theoretical maximum array size of about 2 GB of characters (≈4 GB of memory).
int[] arr1 = new int[10]; // define an array of length 10
int[] arr2 = {1,2,3,4,5}; // length is 5However, the JVM stores literal strings in the constant pool, where the index is a u2 (unsigned 2‑byte) value, limiting the length to 65 535 bytes. Because the JVM also needs one byte for the terminating instruction, the practical compile‑time limit for a literal string is 65 534 characters.
At runtime, strings built dynamically can be as large as the array limit (≈2^31‑1 characters), but literals exceeding 65 534 characters cause a compilation error.
Note: The array index range is 0‑65535, but the JVM requires an extra byte for the end instruction, so the effective compile‑time range is 0‑65534. Runtime concatenated strings are not subject to this limit.
Experiments constructing a 65 534‑character literal confirm that it compiles successfully, while longer literals fail.
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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
