getChars() StringBuffer Example

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.


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 Reply

Your email address will not be published. Required fields are marked *