0

A simple question: What is the maximum size (in bytes or characters) of a String object in Java?

Some background info: I want to build a SQL statement (INSERT INTO tbl VALUES (...), (...), ...) and I don't want to exceed the size of the object.

Barranka
  • 20,547
  • 13
  • 65
  • 83

4 Answers4

7

Strings contain an array of chars, so I think you can have at most 2^31 - 1 characters in a Java String. This is the value of Integer.MAX_VALUE.

Any String larger than that, and you can't even index all of the elements.

jh314
  • 27,144
  • 16
  • 62
  • 82
3

from the source code

class String implements java.io.Serializable {
    private char value[]; // 4 bytes + 12 bytes of array header
    private int offset; // 4 bytes
    private int count; // 4 bytes
}

what ever the value of Integer.MAX_VALUE is (which on most systems will be 2^31 -1)

this requires 4GB of memory though so its a very large amount (java uses 16 bit unicode)

so the minimum of Integer.MAX_VALUE and the available memory

exussum
  • 18,275
  • 8
  • 32
  • 65
2

It sounds like you want to insert many rows. Use a PreparedStatement and batch parameters. https://stackoverflow.com/a/3786127/1172714.

Please note that assembling a SQL statement as a String is a dangerous practice. Instead use a prepared statement http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

Community
  • 1
  • 1
dsh
  • 12,037
  • 3
  • 33
  • 51
  • Thank you. I know it can be dangerous, but this specific program is for my personal use, and I can take the luxury of being "not so formal" ;-) – Barranka Jul 11 '13 at 22:40
1

Theoretically it could be Integer.MAX_VALUE chars long.

Harald K
  • 26,314
  • 7
  • 65
  • 111