getChars() StringBuffer Example


To convert StringBuffer contents to an array of characters with getChars() StringBuffer.

Sometimes, it may be needed to copy a few characters of string content of StringBuffer to an array or to copy the complete StringBuffer into an array. Here, getChars() method comes into usage.

What Java API says about getChars() StringBuffer:
  • public synchronized void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): Copies a few characters from the StringBuffer to the array.

where

  1. int srcBegin: Index number selection in string buffer from which position the copying to start (the beginning position)
  2. int srcEnd: Index number selection in string buffer upto what position the copying should proceed (the ending position in the array)
  3. char[] dst: Name of the destination array into which copying is to be done
  4. int dstBegin: From which index number into the array the copying is to be done (insertion position)
Following getChars() StringBuffer example illustrates the method.
public class Demo
{
  public static void main(String args[])
  {						
   StringBuffer sb1 = new StringBuffer("ABCDEFGHI");
   char ch[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

   System.out.println("Array before copying: "  + new String(ch));  // 0123456789

   sb1.getChars(1, 4, ch, 4);

   System.out.println("Array after copying: "  + new String(ch));  // 0123BCD789
  }
}


getChars() StringBuffer
Output screenshot on getChars() StringBuffer

sb1.getChars(1, 4, ch, 4);

1 indicates the index number of the character present in the StringBuffer from where copying is to be done
4 indicates the index number of the character present in the StringBuffer upto which copying is to be done (as index number starts from 0, it will be 4-1)
ch is the name of the character array
4 indicates the index number in the array from which position the copying should start.

Leave a Comment

Your email address will not be published.