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
189

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 - However, the limitation is platform-dеpеndеnt and can vary basеd on thе Java Virtual Machinе (JVM) implеmеntation and thе undеrlying hardwarе. ... In thе abovе еxamplе, wе usе thе Runtimе class to obtain thе maximum availablе mеmory for thе JVM. Although the theoretical maximum length of a string depends upon available memory, it gets restricted by the constraint imposed by Integer.MAX_Value in real practice.
Discussions

Max length of a String?
So I guess that's the max length of a String. Edwin Martin ... 1 char = 2 bytes not 4 bytes since Java uses 16 bit unicode. I guess it would be Integer.MAX_VALUE but also depends on your available RAM... ... Click to expand... There is no explicit maximum, but the String API won't support Strings ... More on thecodingforums.com
🌐 thecodingforums.com
10
March 9, 2005
How to put a max character length on a string
If the string is a parameter of an object, you can add limiting criteria to the setter method. More on reddit.com
🌐 r/javahelp
9
20
March 9, 2020
Maximum length of a String in Java - Stack Overflow
I am new to Java and I was wondering if there was a way in which I can limit the number of characters entered in a String? I have to create an application for a school project in which I need to use More on stackoverflow.com
🌐 stackoverflow.com
How many characters can a Java String have? - Stack Overflow
Java 9 is going to use a single ... the maximum string length will be halved for them in Java 9, only supporting 1073741823 characters. 2017-07-14T15:35:56.13Z+00:00 ... Save this answer. ... Show activity on this post. I believe they can be up to 2^31-1 characters, as they are held by an internal array, and arrays are indexed by integers in Java. ... The internal implementation is irrelevant - there's no reason why the character data couldn't be stored in an array of longs, for ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
BeginnersBook
beginnersbook.com › 2024 › 06 › java-string-max-size
Java String Max Size
June 1, 2024 - 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 ...
🌐
Quora
quora.com › How-long-can-a-string-be-Java
How long can a string be Java? - Quora
Answer (1 of 2): String in Java can be as big as you want in theory but in practice you will run out of memory. 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 ...
🌐
The Coding Forums
thecodingforums.com › archive › archive › java
Max length of a String? | Java | Coding Forums
March 9, 2005 - Java character takes two bytes, so correct answer would be half of the available heap memory. If available heap exceeds Integer.MAX_VALUE twice then maximum length would Integer. MAX_VALUE. And in case you are constructing the string on the fly using a StringBuffer and do not know the final length of the string the theoretical maximum is 1/3 of the size of the total heap memory that is available to the JVM.
🌐
Javapedia
javapedia.net › Using-String › 719
What is the maximum length of a String in Java?
The maximum length of a String is Integer.MAX_VALUE, which is 2^31 - 1. The return type of String length() method is int and an int could have only Integer.MAX_VALUE as its largest value. Also Integer.MAX_VALUE is the maximum value that could be allocated for an array in Java.
Find elsewhere
🌐
Coderanch
coderanch.com › t › 393042 › java › maximum-length-String
maximum length of String = 32k ? (Beginning Java forum at Coderanch)
January 5, 2003 - Because of the way the JVM spec is laid out there are limits on the constant length and how it is specified. There is a limit for each object based on the java heap. Strings live on the heap, so a single one can never be bigger than the heap. Keep in mind that if copying a large string that the space effectively doubles.
🌐
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.
🌐
YouTube
youtube.com › watch
What is the maximum length of a String in Java? - Cracking the Java Coding Interview - YouTube
Cracking the #Java #Coding #Interview - Question 59: What is the maximum length of a String in Java?Watch all the questions here: https://youtube.com/playlis...
Published   June 2, 2023
🌐
CodeAhoy
codeahoy.com › java › string-length
Java String Length() Method with Examples | CodeAhoy
January 26, 2020 - The length is equal to the number of characters, or Unicode code units in the string. length() counts all characters (char values in a string) including whitespace characters e.g. new line, tabs, etc. The maximum length of a string is bounded by an int which is 2^31 - 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
🌐
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....
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);
🌐
Coderanch
coderanch.com › t › 396355 › java › maximum-length-java-lang-String
is there a maximum length for java.lang.String? (Beginning Java forum at Coderanch)
This was discussed somewhere on JavaRanch a month or two back, I remember writing a quick program to confirm it. In practical terms, RAM limitations crop up before int overflow errors. With repeated doubling of String length, think I crashed my JVM at length of around 2^23.
🌐
Coderanch
coderanch.com › t › 380506 › java › limit-length-Strings
Is there any limit on the length of Strings... (Java in General forum at Coderanch)
July 27, 2006 - 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, ...
🌐
Coderanch
coderanch.com › t › 399912 › java › Max-length-String
Max length for a String? (Beginning Java forum at Coderanch)
June 10, 2005 - Internally, all the implementations of String I've looked at use an int to keep track of the number of characters, meaning that 2GB is a hard limit. Given that many Java implementations have a heap-size limit somewhat less that 2GB, this is not really a problem!