Java String Max Size
In this section, we will discuss what is the maximum size of the string in Java.
In Java, a String can be considered as an array of characters, and the sequence of characters called a string. The String class represents character strings. We cannot change the string once it is created. String objects cannot be shared because they are immutable. For example, consider the following string:
The above string is equivalent to:
The String class provides the length() method that determines the length of the String. The syntax of the method is as follows:
The method returns the length of the string. The length of the string is equal to the number of Unicode units in the string. The Java platform uses the UTF-16 representation in char arrays (each character takes two bytes), String, and StringBuffer classes. In this representation, supplementary characters are represented as a pair of char values, the first from the high-surrogates range, (\uD800-\uDBFF), the second from the low-surrogates range (\uDC00-\uDFFF).
The method returns the length which is of type int. So, the String maximum size is the same as the range of integer data type. The maximum length that would be returned by the method would be Integer.MAX_VALUE.
The size of int in Java is 4 bytes (included a signed bit, i.e. MSB). The range of integer data type is -231 to 231-1 (-2147483648 to 2147483647). Remember that we cannot use negative values for indexing. The indexing is done within the maximum range. It means that we cannot store the 2147483648th character. Therefore, the maximum length of String in Java is 0 to 2147483647. So, we can have a String with the length of 2,147,483,647 characters, theoretically.
Let's find the maximum length of the string through a Java program.
Note: We have not shown the complete output because the output is too long to show.
In the above example, we have used a for loop that executes 1000 times. Inside the try block, we have created an array of Integer.MAX_VALUE-i. After that, we have invoked the fill() method of the Arrays class. It assigns the specified data type value to each element of the specified range of the specified array.
Inside the catch block, we caught the exception (if any) thrown by the fill() method and the getMessage() method prints the message related to the exception.
Each character takes two bytes because Java stores string as UTF-16 codes.
Whether you are appending strings directly or using a StringBuilder (much better), you will occasionally need twice as much memory: one to store the existing string and one to store the new string/buffer when it needs to be expanded.
If we try to insert the value beyond the limit upon doing so, the memory gets overflow and the value that we get will be negative. For example, consider the following program:
Trying to initialize n with value Integer.MAX_VALUE + 1 n = -2147483648