logo

Tamaño máximo de cadena Java

En esta sección, discutiremos ¿Cuál es el tamaño máximo de la cadena en Java?

En Java , a Cadena Puede considerarse como una matriz de caracteres y la secuencia de caracteres denominada cadena. La clase String representa cadenas de caracteres. No podemos cambiar la cadena una vez creada. Los objetos de cadena no se pueden compartir porque son inmutable . Por ejemplo, considere la siguiente cadena:

clase de escáner java
 String str='javatpoint'; 

La cadena anterior es equivalente a:

 char ch[] = {'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't'}; String str = new String(ch); 

La clase String proporciona el método length() que determina la longitud de la cadena. La sintaxis del método es la siguiente:

 public int length() 

El método devuelve la longitud de la cadena. El longitud de la cuerda es igual al número de Unidades Unicode en la cuerda. La plataforma Java utiliza la representación UTF-16 en matrices de caracteres (cada carácter ocupa dos bytes), clases String y StringBuffer. En esta representación, los caracteres suplementarios se representan como un par de valores de caracteres, el primero del rango de sustitutos altos (uD800-uDBFF), el segundo del rango de sustitutos bajos (uDC00-uDFFF).

El método devuelve la longitud que es de tipo int. Entonces, el tamaño máximo de la cadena es el mismo que el rango del tipo de datos entero. La longitud máxima que devolvería el método sería Integer.MAX_VALUE.

El tamaño de int en Java es de 4 bytes (incluido un bit con signo, es decir, MSB). El rango del tipo de datos entero es -231a 231-1 (-2147483648 a 2147483647). Recuerde que no podemos utilizar valores negativos para la indexación. La indexación se realiza dentro del rango máximo. Significa que no podemos almacenar el 2147483648th personaje. Por lo tanto, la longitud máxima de String en Java es 0 al 2147483647 . Entonces, teóricamente podemos tener una cadena con una longitud de 2.147.483.647 caracteres.

Encontremos la longitud máxima de la cadena a través de un programa Java.

StringMaxSize.java

procesamiento en paralelo
 import java.util.Arrays; public class StringMaxSize { public static void main(String args[]) { for (int i = 0; i <1000; i++) { try integer.max_value is a constant that stores the maximum possible value for any integer variable char[] array="new" char[integer.max_value - i]; assign specified data to each element arrays.fill(array, 'a'); creating constructor of string class and parses an into it str="new" string(array); determines print length system.out.println(str.length()); } catch (throwable e) returns detail message this throwable system.out.println(e.getmessage()); prints system.out.println('last: ' + (integer.max_value i)); i); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/05/java-string-max-size.webp" alt="Java String Max Size"> <h4>Note: We have not shown the complete output because the output is too long to show.</h4> <p>In the above example, we have used a for loop that executes 1000 times. Inside the try block, we have created an array of <strong>Integer.MAX_VALUE-i</strong> . 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.</p> <p>Inside the catch block, we caught the exception (if any) thrown by the fill() method and the <strong>getMessage()</strong> method prints the message related to the exception.</p> <p>Each character takes two bytes because Java stores string as UTF-16 codes.</p> <p>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.</p> <p>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:</p> <p> <strong>StringSizeBeyondLimit.java</strong> </p> <pre> public class StringSizeBeyondLimit { public static void main(String[] arg) { try { System.out.println( &apos;Trying to initialize&apos; + &apos; a n with value&apos; + &apos; Integer.MAX_VALUE + 1&apos;); // Try to store value Integer.MAX_VALUE + 1 int n = Integer.MAX_VALUE + 1; // Print the value of N System.out.println(&apos;n = &apos; + n); } catch(Exception e) { System.out.println(e); } } } </pre> <p> <strong>Output:</strong> </p> <pre> Trying to initialize n with value Integer.MAX_VALUE + 1 n = -2147483648 </pre> <hr></1000;>

Producción:

 Trying to initialize n with value Integer.MAX_VALUE + 1 n = -2147483648