java.lang.StringBuffer getChars(int srcBegin,int srcEnd,char[] dst,int dstBegin)

Description :

This java tutorial shows how to use the getChars() method of StringBuffer class under java.lang package.

This method returns get the characters from the buffer from index srcBegin and index srcEnd and put it to the character array dst beginning at index dstBegin.

Method Syntax :

public void getChars(int srcBegin,int srcEnd,char[] dst,int dstBegin)

Parameter Input :

DataType Parameter Description
int srcBegin start copying at this offset.
int srcEnd stop copying at this offset.
char [] dst the array to copy the data into.
int dstBegin offset into dst.

Compatibility Version :

Requires Java 1.0 and up

Java Code Example :

This java example source code demonstrates the use of getChars method of StringBuffer class. Initially the code assigns a string “” as initial contents of the string buffer. Then we use getChars method to get characters from the buffer and put it on the the character array as method argument.


 * This example source code demonstrates the use of 
 * getChars method of StringBuffer class

public class StringBufferGetChars {

	public static void main(String[] args) {

		// initialize the StringBuffer object
		StringBuffer sb = new StringBuffer("");
		System.out.println("Contents of buffer:" + sb);

		int srcBegin = 2;
		int srcEnd = 5;
		int dstBegin = 3;
		char[] destinationArray = new char[10];

		// put initial contents on the buffer
		for (int i = 0; i < 10; i++) {
			destinationArray[i] = '*';

		sb.getChars(srcBegin, srcEnd, destinationArray, dstBegin);
		System.out.println("Contents of the char array ");


Sample Output :

Running the above example source code will give the following output

getchars method example

getchars method example

Exception Scenario :


The above exception will be encountered if one of the following condition is true

  • srcBegin method argumet is negative
  • dstBegin method argument is negative
  • the srcBegin is greater than the srcEnd.
  • srcEnd is greater than this.length().
  • dstBegin+srcEnd-srcBegin is greater than dst.length

Suggested Reading List :

References :