logo

Tamanho máximo da string Java

Nesta seção, discutiremos qual é o tamanho máximo da string em Java.

Em Java , a Corda pode ser considerado como uma matriz de caracteres e a sequência de caracteres chamada de string. A classe String representa cadeias de caracteres. Não podemos alterar a string depois de criada. Objetos string não podem ser compartilhados porque são imutável . Por exemplo, considere a seguinte sequência:

escreva json no arquivo python
 String str='javatpoint'; 

A string acima é equivalente a:

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

A classe String fornece o método length() que determina o comprimento da String. A sintaxe do método é a seguinte:

 public int length() 

O método retorna o comprimento da string. O comprimento da corda é igual ao número de Unidades Unicode na corda. A plataforma Java usa a representação UTF-16 em matrizes char (cada caractere ocupa dois bytes), classes String e StringBuffer. Nesta representação, os caracteres suplementares são representados como um par de valores de caracteres, o primeiro do intervalo de substitutos altos, (uD800-uDBFF), o segundo do intervalo de substitutos baixos (uDC00-uDFFF).

O método retorna o comprimento que é do tipo int. Portanto, o tamanho máximo da String é igual ao intervalo do tipo de dados inteiro. O comprimento máximo que seria retornado pelo método seria Integer.MAX_VALUE.

O tamanho de int em Java é de 4 bytes (incluindo um bit assinado, ou seja, MSB). O intervalo do tipo de dados inteiro é -231para 231-1 (-2147483648 a 2147483647). Lembre-se de que não podemos usar valores negativos para indexação. A indexação é feita dentro do intervalo máximo. Isso significa que não podemos armazenar o 2147483648º personagem. Portanto, o comprimento máximo de String em Java é 0 a 2147483647 . Portanto, podemos ter uma String com comprimento de 2.147.483.647 caracteres, teoricamente.

Vamos encontrar o comprimento máximo da string por meio de um programa Java.

StringMaxSize.java

palíndromo em java
 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;>

Saída:

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