How many characters can a Java String have?

Viewed 328474

I'm trying The Next Palindrome problem from Sphere Online Judge (SPOJ) where I need to find a palindrome for a integer of up to a million digits. I thought about using Java's functions for reversing Strings, but would they allow for a String to be this long?

7 Answers

You should be able to get a String of length

  1. Integer.MAX_VALUE always 2,147,483,647 (231 - 1)
    (Defined by the Java specification, the maximum size of an array, which the String class uses for internal storage)
    OR

  2. Half your maximum heap size (since each character is two bytes) whichever is smaller.

I believe they can be up to 2^31-1 characters, as they are held by an internal array, and arrays are indexed by integers in Java.

Have you considered using BigDecimal instead of String to hold your numbers?

Integer.MAX_VALUE is max size of string + depends of your memory size but the Problem on sphere's online judge you don't have to use those functions

Related