Backend Development 8 min read

Understanding Java String Length Limits and JVM Constant‑Pool Restrictions

This article explains why Java strings have a theoretical maximum size of about 2^31‑1 characters at runtime, but literal strings defined in source code are limited to 65 534 characters due to JVM constant‑pool specifications, and demonstrates the limits with practical experiments.

Architecture Digest
Architecture Digest
Architecture Digest
Understanding Java String Length Limits and JVM Constant‑Pool Restrictions

Java developers often wonder whether the String class has a length limit; the answer is yes, both at runtime and at compile time, and the limits differ because of how strings are stored.

At runtime a String is backed by a char[] array, and the length() method returns an int . Since an int in Java can hold values up to 2^31‑1, the theoretical maximum number of characters is about 2 147 483 647 (roughly 4 GB of memory).

When a string literal is compiled, the JVM places it in the class file’s constant pool. The constant‑pool entry for a string is a CONSTANT_String that references a CONSTANT_Utf8_info structure whose length field is a 2‑byte unsigned value (u2). A u2 can represent at most 2^16‑1 = 65 535, but one byte is needed for the terminating instruction, so the effective limit for a literal is 65 534 characters.

Example code illustrating array creation:

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

The article also shows a small experiment: a string of exactly 65 534 characters is built with a loop, printed, and then assigned to a literal; both compile and run successfully, confirming the compile‑time limit.

In summary, Java strings can be up to 2^31‑1 characters when created at runtime, but source‑code literals are constrained to 65 534 characters because of the JVM constant‑pool’s u2 length field.

backendJavaJVMString()Constant PoolLength Limit
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

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