Fundamentals 8 min read

Why Does Java’s String Have a 65,534‑Character Limit? Deep Dive into JVM Specs

Java’s String length is bounded by both the int‑based array limit (≈2 billion characters) and a JVM compile‑time restriction of 65,534 characters due to the constant‑pool’s u2 index, a nuance explained through source code examples, JVM spec excerpts, and a practical experiment.

ITPUB
ITPUB
ITPUB
Why Does Java’s String Have a 65,534‑Character Limit? Deep Dive into JVM Specs

How String Is Stored

In Java a String is backed by a char[] array, so the characters are stored in a contiguous array of 16‑bit Unicode code units.

Theoretical Array Limit

The length of the backing array is an int, and Java’s int type ranges from -2^31 to 2^31‑1. Because array indices start at 0, the maximum number of elements a char[] can hold is 2^31‑1 (≈2 147 483 647), which corresponds to roughly 4 GB of character data.

int[] arr1 = new int[10]; // define an array of length 10
int[] arr2 = {1,2,3,4,5}; // length is 5

JVM Constant‑Pool Limit

When a string literal is compiled, the JVM stores it in the class file’s constant pool. Each constant‑pool entry is identified by a u2 index, i.e., an unsigned 16‑bit value whose maximum is 2^16‑1 = 65535. The JVM also needs one extra byte for the terminating instruction, so the effective compile‑time limit for a literal string is 65534 characters.

Practical Experiment

To verify the limit, a loop was used to build a string of exactly 65 534 characters, its length was confirmed with a character‑count tool, and the literal was placed directly in source code. The code compiled and ran successfully, demonstrating that the compile‑time limit is indeed 65 534 characters.

Conclusion

In summary, a Java String can hold up to roughly 2 billion characters at runtime because of the int ‑based array limit, but when the string is expressed as a literal in source code the JVM imposes a stricter compile‑time ceiling of 65 534 characters due to the constant‑pool’s u2 index size.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaJVMStringConstant PoolLength Limit
ITPUB
Written by

ITPUB

Official ITPUB account sharing technical insights, community news, and exciting events.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.