Tapas Bose
Tapas Bose

Reputation: 29806

Can String hold greater than Integer.MAX_VALUE number of character

If I want to create a String object which contains x number of character, where x > Integer.MAX_VALUE, can I do that?

Thanks.

Upvotes: 6

Views: 1525

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533520

Instead of storing a single String of length 2 bn (This will use 8 GB of memory to create btw) You can create a collection of Strings. Its not as easy to work with but can effectively be any length.

Upvotes: 3

erencan
erencan

Reputation: 3763

Since String in java is a reference type, strings are stored in a contiguous block of memory. this block must be accessible by integer indices. The memory range must be between 0 and 2^32 -1 in a 32 bits computer architecture which is equal to int primitive data type range.

A basic integer data type can address your memory range. Therefore, you can not store any string which exceeds your memory.

In addition, you can not store any data which exceeds your program stack which is very limited range of memory compared to system memory. you will get stackOverFlow exception when the application memory is exceeded.

Upvotes: 2

amit
amit

Reputation: 178451

Have a look at the source.

the field count, which indicates the string's size is an int - so you will get an overflow.

private final int count;

Upvotes: 5

Related Questions