Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the maximum literal length defined by String in java

Shulou Source: shulou.com Published: 2022-06-03 05:58:02 10月03日 Update

This article to share with you is about Java String definition literal maximum length is how much, Xiaobian think quite practical, so share to everyone to learn, I hope you can read this article after some harvest, not much to say, follow Xiaobian to see it.

Java String object bottom layer is a character array storage, theoretically char[] maximum length is the maximum value of int

Thinking:

First, String literal constants are maintained by the String class and can be determined at compile time (see String constant pool for details). Thus, if there is a maximum length for String literal constants (assumed for now) and we use literal constants that exceed this limit, then the compiler can give an error message during compilation. Therefore, we can use IO stream to generate Java file, the content of the file is to declare a String object, and then use literal constant assignment, according to the dynamic compilation results, adjust the length of the literal constant, and finally get the maximum length value of the literal constant

Draw conclusions based on the following code (code from the book Java Deep Parsing: 36 Topics to Dialyse Java Essence):

import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import javax.tools.JavaCompiler; import javax.tools.ToolProvider; public class LiteralLength { public static void main(String[] args) throws Exception { String fileName = "D:/Literal.java"; StringBuilder prefix = new StringBuilder(); prefix.append ("public class Literal{ String s = \""); int low = 0; int high = 100_0000; int mid =(low + high)/2; StringBuilder literal = new StringBuilder(high); int result; String ch = "A"; JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();//custom error output stream err = new OutputStream() { @Override public void write(int b) throws IOException { } }; int max = 0; for (int i = 0; i < mid; i++) { literal.append(ch); } while(low

Tags: Length compile maximum literal character constant byte success file code result error variable array type proxy output difference between string Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Apple Shulou Tech Info vpn Docker