logo

Максимална величина Јава стринга

У овом одељку ћемо разговарати која је максимална величина стринга у Јави.

Ин Јава , а Низ може се сматрати низом знакова, а низ знакова се назива стрингом. Класа Стринг представља низове знакова. Не можемо променити стринг када је креиран. Стринг објекти не могу да се деле јер јесу непроменљиво . На пример, узмите у обзир следећи низ:

систем.оут.принтлн
 String str='javatpoint'; 

Горњи низ је еквивалентан:

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

Класа Стринг обезбеђује метод ленгтх() који одређује дужину стринга. Синтакса методе је следећа:

 public int length() 

Метод враћа дужину стринга. Тхе дужина жице једнак је броју Уницоде јединице у низу. Јава платформа користи УТФ-16 репрезентацију у низовима знакова (сваки карактер заузима два бајта), Стринг и СтрингБуффер класама. У овој репрезентацији, додатни карактери су представљени као пар вредности цхар, први из опсега високих сурогата (уД800-уДБФФ), други из опсега ниских сурогата (уДЦ00-уДФФФ).

Метод враћа дужину која је типа инт. Дакле, максимална величина стринга је иста као опсег целобројног типа података. Максимална дужина коју би метод вратио би била Интегер.МАКС_ВАЛУЕ.

Величина инт у Јави је 4 бајта (укључује потписани бит, тј. МСБ). Опсег целобројног типа података је -231до 231-1 (-2147483648 до 2147483647). Запамтите да не можемо користити негативне вредности за индексирање. Индексирање се врши у оквиру максималног опсега. То значи да не можемо да складиштимо 2147483648тх карактера. Према томе, максимална дужина стринга у Јави је 0 до 2147483647 . Дакле, теоретски можемо имати стринг дужине 2,147,483,647 карактера.

Хајде да пронађемо максималну дужину стринга кроз Јава програм.

СтрингМакСизе.јава

колико има плодова
 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;>

Излаз:

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