Why Does Java Limit String Literals to 65,534 Characters?
This article explains how Java stores strings using a char array, the theoretical maximum length of 2^31‑1 characters, and why the JVM limits string literals to 65,534 characters due to constant‑pool u2 indexing, illustrated with code examples and a practical experiment.
Introduction
In Java, a String is stored in a char[] array, so its length is bounded by the array size and the return type of String.length(), which is int. Since int ranges up to 2³¹‑1, the theoretical maximum number of characters is about 2 147 483 647 (≈4 GB).
Array Length Limit
Arrays in Java are indexed by int, and the maximum array length is therefore 2³¹‑1. This limit applies to the internal char[] used by String.
int[] arr1 = new int[10]; // define an array of length 10
int[] arr2 = {1,2,3,4,5}; // length is 5JVM Constant‑Pool Restriction
When a string literal is compiled, the JVM stores it in the class file’s constant pool as a CONSTANT_String entry. The constant‑pool index is a u2 (unsigned 2‑byte) value, which can represent at most 65 535 entries. One byte is needed for the terminating instruction, so the effective maximum length of a string literal is 65 534 characters.
Practical Experiment
A small program builds a string of length 65 534 using a loop, prints its length, and then assigns it as a literal. The compilation succeeds, confirming the constant‑pool limit.
In the class file format, the u2 index can represent values 0‑65535. Because the JVM needs one byte for the terminating instruction, the effective usable range for a string literal is 0‑65534. This limit applies at compile time; at runtime, strings built dynamically can be as long as the int limit allows.
Conclusion
While a Java String can theoretically hold up to about 2 147 483 647 characters, the JVM imposes a compile‑time limit of 65 534 characters for string literals due to the constant‑pool u2 index size. Runtime‑generated strings are only limited by the int array size.
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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
