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);
        System.out.println(s.length());
    }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact