What is the maximum length of a String in Java?
Or, in other words:What is the largest String object you can create in Java?
int size = myString.length();In Java, the maximum value of a signed int is approximately 2.14 billion.So, theoretically, a String object in Java can hold a maximum of roughly 2.14 billion characters, assuming that each character is represented by a single byte, such as with Latin-1 encoding for Western languages.
CONSTANT_Utf8_info {
u1 tag;
u2 length;
u1 bytes[length];
}u2 length;u2 means an unsigned 16-bit integer, so its largest possible value is: 65,535For ASCII characters, where each character requires one byte of storage, this suggests that the largest String literal that could theoretically be declared in a Java source file is 65,535 characters.
public class MaxString {
public static void main(String[] args) {
String maxString = "65 thousands characters here...";
System.out.printf("String length: %,d\n", maxString.length());
}
}If you put one extra character into the literal, the Java compiler reports this error:MaxString.java:3: error: constant string too long String maxString = "X0123456789:;<= ..."Did I write this program manually? Of course not.It would be extremely difficult to type and count the exact number of characters by hand, so I created another program instead:
package net.codejava;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class MaxStringGenerator {
public static void main(String[] args) throws Exception {
File file = new File("MaxString.java");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.append("public class MaxString {\n");
writer.append("\tpublic static void main(String[] args) {\n");
writer.append("\t\tString maxString = \"");
int count = 0;
boolean stop = false;
while (!stop) {
for (char c = 48; c <= 90; c++) {
writer.append(c);
if (++count > 65_533) {
stop = true;
break;
}
}
}
writer.append("\";\n\n");
writer.append("\t\tSystem.out.printf(\"String length: %,d\", maxString.length());\n\n");
writer.append("\t}");
writer.append("\n}");
writer.flush();
writer.close();
}
}When you run MaxStringGenerator, it creates a MaxString.java source file that declares a String literal containing exactly 65,534 characters.And this is where things become interesting.
The maximum String literal declared in Java
package net.codejava;
public class LargestString {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Integer.MAX_VALUE - 2; i++) {
sb.append('A');
}
String s = sb.toString();
System.out.printf("String length: %,d", s.length());
}
}Again, I got another unexpected result.If I use the exact value of Integer.MAX_VALUE the program fails with this runtime error:java.lang.OutOfMemoryError: Requested array size exceeds VM limitThis still happens even if I increase the heap size, for example:-Xmx5gFive gigabytes of heap should be enough for the test I was performing.
String length: 2,147,483,645So the largest runtime-created String I could create contained:
2,147,483,645 charactersThat is exactly: Integer.MAX_VALUE - 2This was the second mystery.

Memory consumption when running largest String test
private final byte[] value;We do not need rocket science or advanced mathematics here.A String containing approximately 2.1 billion characters should consume around 2.1 GB of memory if each character is stored using one byte.

Verify the size of the all byte arrays in memory
private final char value[];The primitive char type requires two bytes to represent a single character. That means the maximum memory footprint of a String object containing about 2.1 billion characters could reach roughly 4 GB under JDK 8.That number makes sense.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.