Max size for StringBuffer

喜你入骨 提交于 2019-11-29 04:51:02

because stringbuffer internally uses an array and the maximum number of elements an array can accommodate is 2^31-1 if you increment after reaching this it will go to negative and throws the error

StringBuffer uses a char[].
In Java an array can be indexed only via an integer which means the highest value the index of the array can be is Integer.MAX_VALUE - 1 (i.e. 2^31 - 1). Which means that the size of an array in Java can not be larger than Integer.MAX_VALUE

Answer is different based on System architecture.

This old machine when I posted answer on 2012

Max Length of characters = 37748734

Java Version : 1.6.0_35

OS : Windows 7

System Architecture : 32bits (x86)

RAM : 2 GB

Processor : Pentium Dual Core E5800 3.20GHz

On 2016

Max Length of characters = 301989886

Java Version : 1.8

OS : Ubuntu 14 LTE and Windows 7

System Architecture : 64bits (x86_64)

RAM : 8 GB

Processor : Intel(R) Core(TM) i3-4130 CPU @ 3.40GHz

Run This program your self

        StringBuffer strbTest = new StringBuffer();
        long len = 0;
        try {
            System.out.println("Wait.... til number not generated.");

            while(true) {
                strbTest.append("a");
                len++;
            }
        } catch (OutOfMemoryError e) {
            System.out.println("Max length on your system is "+len);
            System.out.println("Error");
        }
        System.out.println("End");

Output

Max length on your system is 37748734

if you are getting anywhere near 2^31 characters in your buffer you are doing it wrong and you would have run out of memory long ago.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!