Backend Development 8 min read

Understanding Java String Length Limits and JVM Constant‑Pool Restrictions

This article explains how Java strings are stored, the theoretical 2^31‑1 character limit imposed by the underlying char[] array, and the practical 65534‑character limit enforced by the JVM constant‑pool specification, illustrated with code examples and a small experiment.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Understanding Java String Length Limits and JVM Constant‑Pool Restrictions

Java strings are backed by a char[] array, so their theoretical maximum length is bounded by the maximum size of an int‑indexed array (2^31‑1, about 2 GB of characters).

The String.length() method returns an int , and the Integer class shows that the maximum int value is 2^31‑1, confirming the theoretical limit.

However, when a string literal is compiled, the JVM stores it in the class file constant pool, where the CONSTANT_String entry uses a u2 index. A u2 can represent values from 0 to 65535, and one byte is needed for the terminating instruction, so the effective compile‑time limit is 65534 characters.

int[] arr1 = new int[10]; // 定义一个长度为10的数组
int[] arr2 = {1,2,3,4,5}; // 那么此时数组的长度为5

The article shows an experiment that builds a string of exactly 65534 characters via a loop, prints its length, and assigns it to a literal; the compilation succeeds, confirming the constant‑pool limit.

In summary, at runtime a Java String can hold up to about 2 GB of characters (limited by the int index), but when defined as a literal the JVM restricts it to 65534 characters because of the constant‑pool u2 index.

JavaJVMCompilationString()Constant PoolLength Limit
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

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.