Understanding Java String Length Limits and JVM Specification
This article explains Java's String length limitations, detailing how strings are stored as char arrays, the int‑based length method, the JVM class‑file constant pool constraints (u2 index max 65535, effectively 65534), and demonstrates practical experiments confirming these limits.
In this article, the author shares an interview question about whether Java's String has a length limit and, if so, what that limit is, referencing both Java language specifications and JVM compilation rules.
Strings in Java are backed by a char[] array, and the length() method returns an int . Since Java arrays are indexed by integers, the theoretical maximum size of a String is the maximum value of an int (2^31‑1), which corresponds to roughly 4 GB of characters.
However, when a String literal is compiled, it is stored in the class file's constant pool. The constant‑pool entry for a String uses a CONSTANT_Utf8_info structure whose length field is a 2‑byte unsigned value (u2). This limits the literal to 2^16‑1 = 65535 bytes, and because the JVM needs one extra byte for the terminating instruction, the effective compile‑time limit is 65534 characters.
The article includes a small code example showing how to declare arrays in Java:
int[] arr1 = new int[10]; // define an array of length 10
int[] arr2 = {1,2,3,4,5}; // array length is 5To verify the constant‑pool limit, the author built a String of exactly 65 534 characters using a loop, confirmed its length with an online tool, and successfully compiled it as a literal, demonstrating that the compile‑time limit holds.
In summary, a Java String can hold up to about 2^31‑1 characters at runtime (limited by memory), but a String literal cannot exceed 65 534 characters due to the JVM class‑file constant‑pool specification.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
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.