Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Max size for StringBuffer

Why would the StringBuffer have a limit on its size?

I went through some of the links : http://www.coderanch.com/t/540346/java/java/maximum-size-hold-String-buffer.

Is that because of the count member variable, which is an int?

Suppose that we have 2^31-1 chars in StringBuffer and that we append some more chars to that StringBuffer. Count member variable would be incremented by the number of chars appended and if Count variable is already at its max (2^31-1), it would revert back to some negative value.

Why would it throw an error?

like image 257
vjk Avatar asked Aug 10 '12 20:08

vjk


Video Answer


3 Answers

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

like image 77
Dungeon Hunter Avatar answered Oct 12 '22 11:10

Dungeon Hunter


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

like image 37
Cratylus Avatar answered Oct 12 '22 10:10

Cratylus


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
like image 20
Ankur Loriya Avatar answered Oct 12 '22 11:10

Ankur Loriya