3

I am trying to solve a CodeChef problem in Java and found out that I could not create a String with length > one million chars (with my compiler at least). I pasted the first one million decimal digits of Pi in a string (e.g. String PI = "3.1415926535...151") in the Java file and it fails to compile. When I take out the Pi and replace it with a shorter string like "dog", the code compiles. Can anyone confirm if this is indeed a limitation of Java?

Thanks.

  • 1
    Do you have the error message produced from the compiler? – Colin D Aug 21 '13 at 15:15
  • 1
    @RobertH It is not a duplicate of that question. You can programatically create strings larger than the limit on string literals. – Colin D Aug 21 '13 at 15:19
  • without the exact error message, this can be same as this one http://stackoverflow.com/questions/243097/javac-error-code-too-large – Katona Aug 21 '13 at 15:20

2 Answers2

18

Can anyone confirm if this is indeed a limitation of Java?

Yes. There is an implementation limit of 65535 on the length of a string literal1. It is not stated in the JLS, but it is implied by the structure of the class file; see JVM Spec 4.4.7 and note that the string length field is 'u2' ... which means a 16 bit unsigned integer.

Note that a String object can have up to 2^31 - 1 characters. The 2^16 -1 limit is actually for string-valued constant expressions; e.g. string literals or concatenations of literals that are embedded in the source code of a Java program.


If you want to a String that represents the first million digits of Pi, then it would be better to read the characters from a file in the filesystem, or a resource on the classpath.


1 - This limit is actually on the number of bytes in the (modified) UTF-8 representation of the String. If the string consists of characters in the range 0x01 to 0x7f, then each byte represents a single character. Otherwise, a character can require up to 6 bytes.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
-1

I think this problem is not related to string literals but to method size: http://chrononsystems.com/blog/method-size-limit-in-java. According to that, the size of the method can not exceed 64k.

Katona
  • 4,816
  • 23
  • 27
  • It could be method size related, if the string was declared in a method... but there is not indication of that in the question. If it were the case, then OP would have 2 problems. – Colin D Aug 21 '13 at 15:28
  • @ColinD: according to [this](http://www.mail-archive.com/help-bison@gnu.org/msg01990.html), it's valid for static initializer too – Katona Aug 21 '13 at 15:31