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.

Programmer DD
Programmer DD
Programmer DD
Why Does Java Limit String Literals to 65,534 Characters?

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 5

JVM 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.

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
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

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.