Considering the String class' length method returns an int, the maximum length that would be returned by the method would be Integer.MAX_VALUE, which is 2^31 - 1 (or approximately 2 billion.)

In terms of lengths and indexing of arrays, (such as char[], which is probably the way the internal data representation is implemented for Strings), Chapter 10: Arrays of The Java Language Specification, Java SE 7 Edition says the following:

The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

Furthermore, the indexing must be by int values, as mentioned in Section 10.4:

Arrays must be indexed by int values;

Therefore, it appears that the limit is indeed 2^31 - 1, as that is the maximum value for a nonnegative int value.

However, there probably are going to be other limitations, such as the maximum allocatable size for an array.

Answer from coobird on Stack Overflow
Top answer
1 of 7
188

Considering the String class' length method returns an int, the maximum length that would be returned by the method would be Integer.MAX_VALUE, which is 2^31 - 1 (or approximately 2 billion.)

In terms of lengths and indexing of arrays, (such as char[], which is probably the way the internal data representation is implemented for Strings), Chapter 10: Arrays of The Java Language Specification, Java SE 7 Edition says the following:

The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

Furthermore, the indexing must be by int values, as mentioned in Section 10.4:

Arrays must be indexed by int values;

Therefore, it appears that the limit is indeed 2^31 - 1, as that is the maximum value for a nonnegative int value.

However, there probably are going to be other limitations, such as the maximum allocatable size for an array.

2 of 7
32

java.io.DataInput.readUTF() and java.io.DataOutput.writeUTF(String) say that a String object is represented by two bytes of length information and the modified UTF-8 representation of every character in the string. This concludes that the length of String is limited by the number of bytes of the modified UTF-8 representation of the string when used with DataInput and DataOutput.

In addition, The specification of CONSTANT_Utf8_info found in the Java virtual machine specification defines the structure as follows.

CONSTANT_Utf8_info {
    u1 tag;
    u2 length;
    u1 bytes[length];
}

You can find that the size of 'length' is two bytes.

That the return type of a certain method (e.g. String.length()) is int does not always mean that its allowed maximum value is Integer.MAX_VALUE. Instead, in most cases, int is chosen just for performance reasons. The Java language specification says that integers whose size is smaller than that of int are converted to int before calculation (if my memory serves me correctly) and it is one reason to choose int when there is no special reason.

The maximum length at compilation time is at most 65536. Note again that the length is the number of bytes of the modified UTF-8 representation, not the number of characters in a String object.

String objects may be able to have much more characters at runtime. However, if you want to use String objects with DataInput and DataOutput interfaces, it is better to avoid using too long String objects. I found this limitation when I implemented Objective-C equivalents of DataInput.readUTF() and DataOutput.writeUTF(String).

🌐
Baeldung
baeldung.com › home › java › java string › string’s maximum length in java
String’s Maximum Length in Java | Baeldung
June 16, 2025 - This is because Java String length is represented as an int data type: ... In thе abovе snippеt, wе sеt thе maxLеngth variablе to Intеgеr.MAX_VALUE, which rеprеsеnts thе maximum positivе valuе that can bе hеld by an int. Thеrеforе, any attеmpt to crеatе a string longеr than this limit will rеsult in an OutOfMemoryError:
🌐
Coderanch
coderanch.com › t › 380506 › java › limit-length-Strings
Is there any limit on the length of Strings... (Java in General forum at Coderanch)
If you want me to be extremely precise, I should say there are no special limits, aside from the intrinsic limits of the String class: a maximum of 2^31-1 characters, I believe. ... Using a HashMap treats a String as an Object. Hence, ANY String will do, regardless of the length of the string, ...
🌐
Quora
quora.com › How-long-can-a-string-be-Java
How long can a string be Java? - Quora
String has a method, length(), which measures how many characters a specific string has. Its return type is int, so the maximum number of characters in a string can be 2^31 - 1. If you ...
🌐
Medium
medium.com › @umeshcapg › how-many-characters-can-a-java-string-store-in-java-48b85cdf0759
How Many Characters Can a Java String Store in Java? 📜 | by Umesh Kumar Yadav | Medium
July 12, 2025 - The Java compiler (javac) places a strict limit on the size of string literals. This restriction comes from how strings are stored in the .class file's constant pool. Inside the JDK’s compiler source code, the Pool class enforces a maximum byte length for any string encoded in UTF-8 format.
🌐
BeginnersBook
beginnersbook.com › 2024 › 06 › java-string-max-size
Java String Max Size
However, in practice, the actual maximum size of a String is limited by the available memory on the system. Although, you are unlikely to face any issues as the number 2147483647 is huge, however in case, if you are dealing with such huge amount of data then it is better to switch to a different ...
🌐
The Coding Forums
thecodingforums.com › archive › archive › java
Max length of a String? | Java | Coding Forums
March 7, 2005 - Click to expand... class String implements java.io.Serializable { private char value[]; // 4 bytes + 12 bytes of array header private int offset; // 4 bytes private int count; // 4 bytes } The largest number a four-byte signed integer can hold ...
Find elsewhere
🌐
Coderanch
coderanch.com › t › 393042 › java › maximum-length-String
maximum length of String = 32k ? (Beginning Java forum at Coderanch)
Simplistically, yes. Here's a discussion of the topic: String length Linda ... Java has no limit - the JLS does not specify a limit. There is an implicit limitation if one presumes that a String must be implemented as a single array. Because of the way the JVM spec is laid out there are limits ...
🌐
CodeAhoy
codeahoy.com › java › string-length
Java String Length() Method with Examples | CodeAhoy
January 26, 2020 - The maximum length of a string is bounded by an int which is 2^31 - 1. In other words, a string can have a maximum of 2 billion characters. In the following example, we call the length method on a String object.
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-string-length-method-example
Java String length() Method with examples
This method counts the number of ... (length) in a given string including white spaces. String length limit: The maximum length a string can have is: 231-1....
🌐
Codemia
codemia.io › knowledge-hub › path › strings_maximum_length_in_java_-_calling_length_method
String's Maximum length in Java - calling length method
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
Top answer
1 of 4
7

Not taking the comma and the ellipses into account when calculating the resulting string length and instead setting the max length to 250 is an ugly hack. The code is also a bit buggy, because if the first error message happens to be 250 characters long, you only get ellipses in the result even though there would have been room for the error message, a comma and ellipses.

You should create a method for calculating the result length if a string was appended.

private int calculateResultingLength(String str) {
    int result = stringBuilder.length();
    if (result > 0) {
        result += 1; // Account for a comma.
    }
    if (errorsDropped) {
        result += ELLIPSES.length();
    }
    result += str.length();

    return result;
}

The second isFull check in checkAndAppend is redundant because you already do that check in the append method and checkAndAppend is private. The isFull is now also misleading, because it tells that an error was dropped. The next error might be shorter and fit into the string. I rename it to errorsDropped.

public void append(String str) {
    if (calculateResultingLength(str) >= MAX_CAP) {
        errorsDropped = true;
    } else {
        performAppend(str);
    }
}

The isFirst field is redundant. You know the append is the first one if the stringBuilder is empty:

private void performAppend(String str) {
    if (stringBuilder.length() > 0) {
        stringBuilder.append(",");
    }
    stringBuilder.append(str);
}

The performAppend method became a bit pointless now. You could just write:

public void append(String str) {
    if (calculateResultingLength(str) >= MAX_CAP) {
        errorsDropped = true;
        return;
    }

    if (stringBuilder.length() > 0) {
        stringBuilder.append(",");
    }
    stringBuilder.append(str);
}

The MAX_CAP and ELLIPSES are named as if they were constants but they are variables. They should be static and final. Also, no need to abbreviate here.

private static final int MAX_CAPACITY = 255;
private static final String ELLIPSES = "...";
2 of 4
5

Test naming

Consider dropping 'test' from the front of your test names and using the extra space to add something describing the expected outcome for the test, maybe something like...

append_overflowMaxLength_maxLengthNotExceeded
append_withinBuffer_addsMessage
append_overflowMaxLength_entireExceptionReplacedWithElipses

assertEquals

You're passing your parameters to assertEquals the wrong way round (your expected is your actual). Frameworks like assertJ can make assertions more intuitive.

assertThat(result).isEqualTo("...");
assertThat(result).endsWith("...");
assertThat(result).hasSizeLessThan(255);
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › String › length
Java String length() - Get String Length | Vultr Docs
December 17, 2024 - The for loop iterates over each character in the string phrase by using length() to limit the loop range. This method allows access to each character sequentially, which is useful for parsing or modifying strings. The length() method in Java's String class is critically useful for controlling ...