What is the maximum string length in Java?

Chandra Patni

Strings are represented as character array. Therefore, theoretical limit of String length is java.lang.Integer.MAX_VALUE. However, in most machines you will run out of memory before you could create such a big String.

I use java -Xms256m -Xmx384m MaxStringLength to run the following code successfully. :)

public class MaxStringLength {
    public static void main(String args[]) {
        int len = Integer.MAX_VALUE/30;
        char ch[] = new char[len];
        for(int i = 0; i < len; i++) {
            ch[i] = 'a';
        String s = new String(ch);