12

Possible Duplicate:
String's Maximum length in Java - calling length() method

I have a string defined as

String xx

Is there any limit for the number of characters that I can assign?

2) I am assigning the user input to this string xx. 70% of the times people give only one word. some times they give a big sentence so want to know is that ok? or is there any better java practices?

Community
  • 1
  • 1
The Learner
  • 3,867
  • 14
  • 40
  • 50
  • 1
    Did you even briefly Google this before posting? The second hit for `java string length limit` was the duplicate listed above. – Duncan Jones Aug 25 '12 at 07:20
  • If you have to ask, you're already doing the wrong thing. Strings shouldn't be treated as containers. – user207421 Aug 25 '12 at 08:22

1 Answers1

36

A common question you could have searched for but I going to answer it again anyway.

Is there any limit for the number of characters that I can assign?

Its Integer.MAX_VALUE or 2^31-1 or about 2 billion. You are more likely to have memory problems before getting to this size. e.g. You need 4 GB for the String and 4 GB to create it.

I am assigning the user input to this string xx. 70% of the times people give only one word. some times they give a big sentence so want to know is that ok?

I suspect all the works of J K Rowling would fit into one string.

or is there any better java practices?

I suggest you keep things as simple as possible. Assigning a String reference is about simple as it gets.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Keep in mind that if the heap size, divided by the size of `char` (which is 2), is smaller than `Integer.MAX_VALUE`, that will be the upper bound instead. – Cat Aug 25 '12 at 07:20
  • @Eric So "much more than a sentence" .. ;-) –  Aug 25 '12 at 07:21
  • @Eric True, as I mentioned you need 4 bytes for every char you want in the strings. (2 bytes for the String and 2 bytes to build it) – Peter Lawrey Aug 25 '12 at 07:22
  • @PeterLawrey Ah, yes, I didn't realize where you had pulled these numbers from. Thanks for clarifying. – Cat Aug 25 '12 at 07:26
  • 2
    And you need a **contiguous heap segment** for each of those 4GB blocks, so even an 8GB heap may not cut it. – Marko Topolnik Aug 25 '12 at 09:29
  • The CMS collector doesn't de-fragment memory so you can get this problem. – Peter Lawrey Aug 25 '12 at 09:33
  • 1
    congrats, your answer is now the top google search result. so most people who find this answer actually did search for it! – smcg May 12 '16 at 21:55