Hi everyone,

I have a rather silly question but what is the maximum amount of characters the String object can hold?

This is what i mean

String str1 = some buffer that contains about 5 million characters as a string

What i am afraid is that if the String object may throw an exception if i return a huge string object say something down the lines of 5-50 million characters as a string. Will there be stack overflow?

I hope someone can help me with this

Thank You

Yours Sincerely

Richard West

Recommended Answers

All 5 Replies

There is no size limitation of Strings sizes. Only the limitation of heap size..Which I'm guesing is JVM independant?

heap size is dependent mainly on the amount of memory available to the JVM.

Of course such huge strings are pretty useless. Remember Strings in Java are immutable so anything you do to them will create at least one duplicate (effectively creating another String of the same size every time you do anything with it that changes the data).

Best use either a StringBuilder or some other buffering system to hold the data in a more flexible manner.

Hi everyone,

The reason why i am using the string in this way is because the object that is returning the huge string is a document.

String str1 = JTextPane.getText();

Why i need this is because i use this method to search the document for a certain string. Everything works but i am afraid that if the document returns a huge string from the document, i may actually exceed the limit.

On another issue i also felt that because the String object is immutable would it be better if i use the StringBuffer class as that does not create a copy of the string something like that

StringBuffer str1 = new StringBuffer(JTextPane.getText());

Would tis actually make a difference in that the String object is immutable and the StringBuffer object is mutable?

Any help is greatly appreciated

Thank You

Yours Sincerely

Richard West

You'd in that case have the worstcase scenario of 2 copies of the entire dataset, one in the immutable string in your Swing control, the other mutable in your StringBuffer.

It might be preferable to subclass your Swing control to work directly on a StringBuffer.

The name of any variable is limited by the underlying compilers string settings, I believe this is 2^64... This is obviously unrelated.

Both String and StringBuffer classes are backed by a char array. The max length of any array is (2^31)-1. So as far as capacity goes, no difference.

Since getText() returns a String, it will actually be limited by these constraints before you get it. Because this method returns a String, this method will throw an exception and return null, if you have a large file. So you really don't have to worry about this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.