Maximum number of characters in a String and Stringbuffer in Java

Asked

Viewed 5,399 times

4

What is the maximum limit of characters that the types String and StringBuffer support in Java?

2 answers

4


The theoretical limit is the maximum value of a int - 2^31-1 - since strings are represented internally by an array of char, and the way to index this array is through a int. However, what will limit in practice the size of the strings is the physical space (RAM), which will certainly be much smaller than this theoretical limit.

I don’t know how the StringBuffer is represented internally, but although it has representation capable of withstanding more than the limit mentioned, the way of referring to a particular character (charAt) still uses a int, so that the same limit can be considered in practice.

  • So what would be the main difference between the two?

  • 1

    One String is immutable, so that you can share references of it freely. A StringBuffer and StringBuilder are mutable, you edit the string at will to - only at the end - turn into a String (if need). The StringBuffer is thread-safe, and the StringBuilder is not. More information about its operation in this related question

  • 1

    for documentation: Stringbuffer is implemented using arrays, and according to the specification, in what it says about arrays: The variables contained in an array have no names; instead they are referenced by array access expressions that use non-negative integer index values.

  • 2

    @wryel When you said you didn’t know how StringBuffer functioned internally, I was referring to the possibility of using string arrays for example - which would imply a theoretical total capacity greater than the size of a int. But you’re right, it’s just a character array, with "space left".

  • Good. Now the subject for me is to realize at a low level what a String be immutable.

  • 1

    @Cold I never reflected deeply on the subject, I simply took that "there are no methods in the API of String to modify it" and I was pleased with it... Now, in practice, there may be optimizations made by the JVM or things like that. If you are interested, I suggest to open a separate question, so who has more knowledge on the subject can answer (I do not have).

  • Questioning the true meaning of String be imutavel @mgibsonbr?

  • 3

    @Cold this may help you: http://answall.com/questions/15510/o-que-imut%C3%A1vel-really-means/15512#15512

Show 3 more comments

2

The maximum limit they both support is 2 31-1 (or about 2 billion)

String concatenation efficiency Stringbuffer

  • And what’s the difference between them if they have the same ability?

  • 1

    http://www.oficinadanet.com.br/post/2124-java_diferencas_entre_as_classes_string_stringbuffer_e_stringbuilder

  • http://www.devmedia.com.br/diferencas-entre-string-stringbuilder-e-stringbuffer-em-java/29865

Browser other questions tagged

You are not signed in. Login or sign up in order to post.