tags:

views:

1250

answers:

4

Hi people.

My question is very basic, but I didn't find an answer on a Google search.

In Java, ¿what is the maximum size a String object may have, referring to the length() method call?

I know that length() return the size of a String as a char [ ]

+5  A: 

Since arrays must be indexed with integers, the maximum length of an array is Integer.MAX_INT, or 2 147 483 647. This is assuming you have enough memory to hold an array of that size, of course.

Michael Myers
+5  A: 

Considering the String class' length method returns an int, the maximum length that would be returned by the method would be Integer.MAX_VALUE, which is 2^31 - 1.

In terms of lengths and indexing of arrays, (such as char[], which is probably the way the internal data representation is implemented for Strings), Chapter 10: Arrays of The Java Language Specification, Second Edition says the following:

The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

Furthermore, the indexing must be by int values, as mentioned in Section 10.4:

Arrays must be indexed by int values;

Therefore, it appears that the limit is indeed 2^31 - 1, as that is the maximum value for a nonnegative int value.

However, there probably are going to be other limitations, such as the maximum allocatable size for an array.

coobird
Integer.MAX_VALUE is 2^31-1, actually. :)
Michael Myers
You're absolutely correct! Thanks for pointing that out, I've fixed the my answer.
coobird
Great answer man! I took a look on String.java source code and it's right, 'count' is the int variable who returns the length of the char array, and the char array is stored on the 'value' variable (as char [ ]) It means that the String size could be around 2GB. Of course there could be limitations to allocate such memory size. Thanks!
taichi
The maximum allocatable size for an array is Integer.MAX_VALUE The maximum size for an array and a String is the same. Note: each character uses two bytes and to build this string you need another two bytes. e.g. using StringBuilder or a plain char[] so you need over 8 GB to create a maximum length string.
Peter Lawrey
As applications get larger, the Integer.MAX_VALUE will be a limitation. There isn't an obvious way around this unfortunately. You could create a LongString using an char[][] i.e. without increasing the maximum length of an array. However, it would be a better solution if an array had a maximum length of Long.MAX_VALUE
Peter Lawrey
Thanks for pointing it out Peter! Great Comment!
taichi
A: 

apparently it's bound to an int, which is 0x7FFFFFFF (2147483647).

Francis
A: 

all wrong, it's 65536