Learn StringBuffer Class in Java: Lecture 7

With this article, the series ends after teaching a few more methods used in the Java StringBuffer class by illustrating simple code examples.
  
Before reading further, read the following previous parts of the series.
Now the next methods of discussion are the following:
  • Java StringBuffer capacity()
  • Java StringBuffer ensureCapacity(int minimumCapacity)
Figure 1 Capacity
 
The int capacity() method returns the current capacity of the buffer. Here, the capacity is an amount of storage available for the newly inserted characters, beyond which allocation will occur.
 
The default capacity of the buffer is 16 characters. If the number of characters increases in the buffer from its current capacity, then it increases the capacity by (defaultCapacity+2) if the current capacity is equal to Default capacity or (oldCapacity+2) if the current capacity is different than the default capacity. For example, if the current capacity is 20 and the number of characters is increased by 2 then it will be (20+2)=42.
 
The void ensureCapacity(int minimumCapacity) method ensures that the given capacity is the minimum of the current capacity. If the current capacity is less than the argument, then a new internal array is allocated with greater capacity. The new capacity is larger than the minimum capacity and it is (oldCapacity*2)+2. If the minimumCapacity argument is zero (0) or a negative then it makes no changes and simply returns the current capacity.
 
Have a look at a sample code example to get a clear picture of the methods.
 
Example: int capacity()
  1. public class CapacityMethod   
  2. {  
  3.     public static void main(String args[])   
  4.     {  
  5.         StringBuffer str = new StringBuffer();  
  6.         System.out.println("Output for int capacity():");  
  7.         System.out.println();  
  8.         System.out.println("Default capacity of buffer is: " + str.capacity()); //return default value 16  
  9.         str = new StringBuffer("java");  
  10.         System.out.println("Buffer is: " + str);  
  11.         System.out.println("Current capacity of buffer is: " + str.capacity()); //return 16+4=20  
  12.         str = new StringBuffer(" ");  
  13.         System.out.println("Buffer is: " + str);  
  14.         System.out.println("Current capacity of buffer is: " + str.capacity()); //return 16+1=17  
  15.         StringBuffer str1 = new StringBuffer("Last lecture");  
  16.         System.out.println("Buffer is: " + str1);  
  17.         System.out.println("Current capacity of buffer is: " + str1.capacity()); //returns current capacity of buffer i.e. 16+12=28  
  18.         str1 = new StringBuffer("Last lecture of the series");  
  19.         System.out.println("Buffer is: " + str1);  
  20.         System.out.println("Current capacity of buffer is: " + str1.capacity()); //returns current capacity of buffer that i.e. 16+26=42  
  21.     }  
  22. }
Output
 
Figure 2
 
Example: void ensureCapacity(int minimumCapacity)
  1. public class EnsureCapacityMethod {  
  2.     public static void main(String args[]) {  
  3.         StringBuffer str = new StringBuffer();  
  4.         System.out.println("Output for void ensureCapacity(int minimumCapacity):");  
  5.         System.out.println();  
  6.         System.out.println("Default capacity of buffer is: " + str.capacity()); //return default value 16  
  7.         str.ensureCapacity(12); //no change will occur because given capacity is less than default capacity  
  8.         System.out.println("Now capacity of buffer is: " + str.capacity()); //return default value again  
  9.         str.ensureCapacity(18); //now change will occur because given capacity is greater than default capacity  
  10.         System.out.println("Now capacity of buffer is: " + str.capacity()); //return (16*2)+2=34  
  11.         StringBuffer str1 = new StringBuffer("Last lecture");  
  12.         System.out.println("Buffer is: " + str1);  
  13.         System.out.println("Current capacity of buffer is: " + str1.capacity()); //returns current capacity of buffer i.e. 16+12=28  
  14.         str1.ensureCapacity(32); //increase the current capacity as ensured capacity (32) is greater than the current capacity (28)  
  15.         System.out.println("Now capacity of buffer is: " + str1.capacity()); //return (28*2)+2=58  
  16.         str1 = new StringBuffer("Last lecture of the series");  
  17.         System.out.println("Buffer is: " + str1);  
  18.         System.out.println("Current capacity of buffer is: " + str1.capacity()); //returns current capacity of buffer that i.e. 16+26=42  
  19.         str1.ensureCapacity(39); //returns current capacity (42) as ensured capacity (39) is less than the current capacity (42)  
  20.         System.out.println("Now capacity of buffer is: " + str1.capacity()); //return 42  
  21.     }  
  22. }
Output
 
 
Figure 3
 
The following are the next methods for discussion. 
Figure 4
 
Methods: reverse() & replace()
 
The reverse() method returns the string by replacing the given string by its reverse format, or we can say that the string is reversed by this method.
 
The replace(int start, int end, String str) method is used to replace the characters of the substring or substring of the given string with the specified characters or substrings.
The characters of substrings begin at the startIndex and extend to the characters at endIndex-1 or to the end of the given sequence if no such character exists. The characters in the substring are removed first and then specified string or characters are inserted at startIndex. It throws StringIndexOutOfBoundsException() if startIndex is negative or greater than the length of the given sequence or greater than endIndex.
 
Example
 
In this example, both methods are explained.
  1. public class ReverseReplaceMethods {  
  2.     public static void main(String args[]) {  
  3.         StringBuffer str1 = new StringBuffer("Remember me");  
  4.         System.out.println("Output for reverse():");  
  5.         System.out.println();  
  6.         System.out.println("Buffer is: " + str1);  
  7.         System.out.println("Reversed buffer is: " + str1.reverse()); //print reversed StringBuffer  
  8.         str1 = new StringBuffer("9876543210");  
  9.         System.out.println("Buffer is: " + str1);  
  10.         System.out.println("Reversed buffer is: " + str1.reverse()); //print reversed StringBuffer  
  11.         str1 = new StringBuffer("pop");  
  12.         System.out.println("Buffer is: " + str1);  
  13.         System.out.println("Reversed buffer is: " + str1.reverse()); //returned StringBuffer is equivalent to original StringBuffer  
  14.         System.out.println();  
  15.         System.out.println("Output for replace(int start, int end , String str):");  
  16.         System.out.println();  
  17.         StringBuffer str2 = new StringBuffer("Welcome to this article");  
  18.         System.out.println("Buffer is: " + str2);  
  19.         str2.replace(11, 15, "my"); //string replacement  
  20.         System.out.println("After replacement: " + str2);  
  21.         str2 = new StringBuffer("Welcome to this article");  
  22.         str2.replace(3, 7, "l done"); //string replacement  
  23.         System.out.println("After replacement: " + str2);  
  24.         str2 = new StringBuffer("Welcome to this article");  
  25.         str2.replace(0, 1, "T"); //character replacement  
  26.         System.out.println("After replacement: " + str2);  
  27.         str2 = new StringBuffer("123000789");  
  28.         System.out.println("Buffer is: " + str2);  
  29.         str2.replace(3, 6, "456"); //character replacement  
  30.         System.out.println("After replacement: " + str2);  
  31.     }  
  32. }
Output
 
 
Figure 5
 
Methods: setLength() & setCharAt()
 
The setLength(int newLength) method sets the new length of the given character sequence whose length is specified by the newLength argument. If the argument is greater than or equal to the current length then sufficient null characters ("\u0000") are appended so that the length becomes newLength argument. It throws IndexOutOfBoundsException() if newLength of the argument is negative.
 
The setCharAt(int index, char ch) method sets the characters at the specified index position to the character ch. The given sequence is altered to represent the new sequence that is similar to the originally given sequence, except that it contains ch as the character at the index position. It throws IndexOutOfBoundsException() if the index is negative or greater than or equal to the length of the given sequence.
 
Example
 
In this example, both methods are explained.
  1. public class SetLengthSetCharAtMethods {  
  2.     public static void main(String args[]) {  
  3.         StringBuffer str1 = new StringBuffer("Remember me");  
  4.         System.out.println("Output for setLength(int newLength):");  
  5.         System.out.println();  
  6.         System.out.println("Buffer is: " + str1);  
  7.         System.out.println("Length of buffer is: " + str1.length()); //print reversed StringBuffer  
  8.         str1.setLength(8); //set the length of StringBuffer 11 to 8  
  9.         System.out.println("New Buffer is: " + str1);  
  10.         System.out.println("New length of buffer is: " + str1.length()); //print reversed StringBuffer  
  11.         str1 = new StringBuffer("9876543210");  
  12.         System.out.println("Buffer is: " + str1);  
  13.         System.out.println("Length of buffer is: " + str1.length()); //print reversed StringBuffer  
  14.         str1.setLength(4); //set the length of StringBuffer 10 to 4  
  15.         System.out.println("New Buffer is: " + str1);  
  16.         System.out.println("New length of buffer is: " + str1.length()); //print reversed StringBuffer  
  17.         System.out.println();  
  18.         System.out.println("Output for setCharAt(int index, char ch):");  
  19.         System.out.println();  
  20.         StringBuffer str2 = new StringBuffer("Things");  
  21.         System.out.println("Buffer is: " + str2);  
  22.         System.out.println("Character at index 4: " + str2.charAt(4));  
  23.         str2.setCharAt(4, 'k');  
  24.         System.out.println("After setting character 'k' at index 4: " + str2);  
  25.         System.out.println("Now character at index 4: " + str2.charAt(4));  
  26.         str2 = new StringBuffer("7n3");  
  27.         System.out.println("Buffer is: " + str2);  
  28.         System.out.println("Character at index 1: " + str2.charAt(1));  
  29.         str2.setCharAt(1, 'g');  
  30.         System.out.println("After setting character 'g' at index 1: " + str2);  
  31.         System.out.println("Now character at index 1: " + str2.charAt(1));  
  32.     }  
  33. }
Output
 
 
 
Figure 6
 
Methods: subSequence() & getChars()
 
The subSequence(int start, int end) method returns a new character sequence that is a subsequence of the given character sequence that is done by start and end indices. It throws IndexOutOfBoundsException() if start or end is negative or end is greater than the sequence length or the start is greater than the end.
 
The getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method copies the characters from the given sequence into the destination dst char array. The first character is to be copied at index scrBegin whereas the last character is to be copied at the index srcEnd-1. So the total numbers of characters to be copied is srcEnd-srcBegin. The characters copied into the subarray of destination dst starts at the index dstBegin and ends at the index dstBegin+( srcEnd-srcBegin)-1. This method can throw either of the following two exceptions: 
  • NullPointerException() if destination dst is found null.
  • IndexOutOfBoundsException() if the following are found:
  1. srcBegin is negativ
  2. dstBegin is negative
  3. srcBegin argument > srcEnd argument
  4. srcEnd >this.length()
  5. dstBegin+srcEnd-srcBegin > dst.length
Example
 
In this example, both methods are explained.
  1. public class SubSeqGetCharsMethods {  
  2.     public static void main(String args[]) {  
  3.         StringBuffer str1 = new StringBuffer("Authorization");  
  4.         System.out.println("Output for subSequence(int start, int end):");  
  5.         System.out.println();  
  6.         System.out.println("Buffer is: " + str1);  
  7.         CharSequence cs1;  
  8.         cs1 = str1.subSequence(0, 6); // return specified subSequence  
  9.         System.out.println("subSequence is: " + cs1); //print the subSequence  
  10.         str1 = new StringBuffer("abcd123efgh");  
  11.         System.out.println("Buffer is: " + str1);  
  12.         CharSequence cs2;  
  13.         cs2 = str1.subSequence(4, 7);  
  14.         System.out.println("subSequence is: " + cs2); //print reversed StringBuffer  
  15.         System.out.println();  
  16.         System.out.println("Output for getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) ):");  
  17.         System.out.println();  
  18.         StringBuffer str2 = new StringBuffer("Learning code ");  
  19.         System.out.println("Buffer is: " + str2);  
  20.         char[] cAR = new char[] {  
  21.             'J''a''v''a'' ''l''a''n''g''s'  
  22.         };  
  23.         str2.getChars(9, 13, cAR, 5);  
  24.         System.out.print("After copying the characters: ");  
  25.         System.out.println(cAR);  
  26.     }  
  27. }
Output
 
 
Figure 7
 
Your patience is appreciated.
 
Thank you, keep learning and sharing.