Controlling String Builder Capacity – Selected API Classes 05/22/2022 Rivka Scheinberg Post in Garbage Collection,Oracle Exams Controlling String Builder Capacity The following methods are exclusive to the StringBuilder class and can be used to control various capacity-related aspects of a string builder: int capacity() Returns the current capacity of the string builder, meaning the number of characters the current builder can accommodate without allocating a new, larger array to hold characters. Click here to view code image void ensureCapacity(int minCapacity) Ensures that there is room for at least a minCapacity number of characters. It expands the string builder, depending on the current capacity of the builder. void trimToSize() Attempts to reduce the storage used for the character sequence. It may affect the capacity of the string builder. Click here to view code image void setLength(int newLength) Ensures that the actual number of characters—that is, the length of the string builder—is exactly equal to the value of the newLength argument, which must be greater than or equal to 0. This operation can result in the string being truncated or padded with null characters (‘\u0000’). This method affects the capacity of the string builder only if the value of the parameter newLength is greater than the current capacity. Example 8.5 illustrates the various capacity-related methods of the StringBuilder class. It is instructive to go through the output to see how these methods affect the length and the capacity of a string builder. Example 8.5 Controlling String Builder Capacity Click here to view code image public class StringBuilderCapacity { public static void main(String[] args) { StringBuilder builder = new StringBuilder(“No strings attached!”); System.out.println(“Builder contents: ” + builder); System.out.println(“Builder length: ” + builder.length()); System.out.println(“Builder capacity: ” + builder.capacity()); System.out.println(“Ensure capacity of 40”); builder.ensureCapacity(40); System.out.println(“Builder capacity: ” + builder.capacity()); System.out.println(“Trim to size”); builder.trimToSize(); System.out.println(“Builder length: ” + builder.length()); System.out.println(“Builder capacity: ” + builder.capacity()); System.out.println(“Set length to 10”); builder.setLength(10); System.out.println(“Builder length: ” + builder.length()); System.out.println(“Builder contents: ” + builder); System.out.println(“Set length to 0”); builder.setLength(0); System.out.println(“Builder is empty: ” + (builder.length() == 0)); }} Probable output from the program: Click here to view code image Builder contents: No strings attached!Builder length: 20Builder capacity: 36Ensure capacity of 40Builder capacity: 74Trim to sizeBuilder length: 20Builder capacity: 20Set length to 10Builder length: 10Builder contents: No stringsSet length to 0Builder is empty: true