3

I know string enjoyed some privilege and it is defined as class in java. As reference to that post Is there any limit for string size in a Java program? String has a size of around 2^31-1.So my question is that how a class has limited size allocation because as i know a class can allocate as many memory blocks as it is required

Community
  • 1
  • 1
ivan R
  • 296
  • 2
  • 16

1 Answers1

5

Internally, the String class contains an array of characters (char[]), which actually is the content the String instance represents.

Java is designed (and often criticized) in such way so that it does not support arrays of size more than Integer.MAX_VALUE (which is exactly 231 - 1).

So, to summarize, the limit of the size of internal char[] array is actually the limit of the size of the String.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • So even though String is a class but it is implemented in same as a c style internally,and it can be crashed if size of string is greater than 2^31-1 – ivan R Dec 23 '15 at 13:36
  • Seems so, yes. You can try it out, if you wish - you'd get an `OutOfMemoryError`. – Konstantin Yovkov Dec 23 '15 at 13:45
  • Another food for thought could be the question - Why one would maintain a `String` that could be so huge, instead of implementing a data structure that can replace the single `String`? :) – Konstantin Yovkov Dec 23 '15 at 13:47
  • and it is the double in bytes: char=2bytes - http://stackoverflow.com/questions/9699071/what-is-the-javas-internal-represention-for-string-modified-utf-8-utf-16 – guillaume girod-vitouchkina Dec 23 '15 at 13:51