How to fix SDK error "constant string too long"?

When we try to use a variable that is too long for the Java compiler (larger than 64 KB) we receive a “constant string too long” error from the compiler. The length of a string constant in a class file is limited to 2^16 bytes in UTF-8 encoding

 

1. Describing the Problem

For example, errors when implementing the compiling 

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.058 s
[INFO] Finished at: 2024-07-24T17:56:34+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:testCompile (default-testCompile) on project core-java-strings: Compilation failure
[ERROR] <path to the test class>:[10,32] constant string too long

 

2. Solving the Problem

Once we have the problem reproduced, let’s find a way to solve it. The best way is to store our string in a separate file instead of a declared variable or constant.

Let’s create a text file to store the content of our variable and modify our test to get the value from the file:

The sample code for reading a file into a string is:
 
public String readLicenseFile(Context context) {
  AssetManager assetManager = context.getAssets();
  StringBuilder stringBuilder = new StringBuilder();
  try (InputStream inputStream = assetManager.open("license");
     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)))
       {
          String line;
          while ((line = bufferedReader.readLine()) != null)
            {
            stringBuilder.append(line);
            stringBuilder.append('\n');
            }
     }
catch (IOException e)
  {
e.printStackTrace();
  }
return stringBuilder.toString();
  }
 

Now if we try to compile our project or execute the tests, everything will work:

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.433 s
[INFO] Finished at: 2024-07-24T18:23:54+01:00
[INFO] ------------------------------------------------------------------------

 

3. Conclusion

In this article, we examined the "constant string too long" compile error. As a solution, we explored the option of storing the values of the strings in separate files or configuration properties.

Was this article helpful?
0 out of 3 found this helpful

Comments

0 comments

Please sign in to leave a comment.