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.

0

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Assuming you have sufficient memory available.
That one String would be roughly 4GB if I did the math correctly.
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

Comments

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

1 Comment

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" ;-)
1

Theoretically it could be Integer.MAX_VALUE chars long.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.