Why Does Java’s String Have a 65,534‑Character Limit? Uncover the JVM Rules
This article explains how Java stores strings using a char array, the theoretical 4 GB limit from the int type, and the JVM’s compile‑time constant‑pool restriction that caps literal strings at 65,534 characters, plus a practical experiment confirming the limit.
Preface
In Java, the String class has a length limit, which many developers encounter during interviews or real‑world coding, such as when storing large Base64‑encoded files as strings.
String
Strings are backed by a char[] array. The array length is limited by the maximum value of an int (2^31‑1), which corresponds to roughly 4 GB of characters.
However, the Java Virtual Machine imposes additional constraints on string literals stored in the class file constant pool.
The length() method of String returns an int, and arrays in Java can have lengths from 0 to 2^31‑1.
int[] arr1 = new int[10]; // define an array of length 10
int[] arr2 = {1,2,3,4,5}; // array length is 5The JVM constant pool uses a u2 index (an unsigned 2‑byte value) to reference strings, limiting the index to 2^16‑1 = 65,535. Because the JVM also needs one byte for the end‑of‑instruction marker, the effective maximum length for a string literal is 65,534 characters.
When a string literal exceeds this limit, the compiler throws an error, even though at runtime a string can be much larger.
To verify, an experiment builds a string of exactly 65,534 characters via a loop, prints its length, and assigns it as a literal. The compilation succeeds, confirming the limit.
Note: The array index range is technically 0‑65,535, but the JVM requires one extra byte for the terminating instruction, so the usable range for string literals is 0‑65,534. This restriction applies only at compile time; runtime‑generated strings can exceed it.
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.
