StringBuffer getChars() method in Java with Examples (original) (raw)

Last Updated : 17 Nov, 2022

The getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method of StringBuffer class copies the characters starting at the index:srcBegin to index:srcEnd-1 from actual sequence into an array of char passed as parameter to function.

Syntax:

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

Parameters: This method takes four parameters:

Returns: This method returns nothing. Exception: This method throws StringIndexOutOfBoundsException if:

Below programs demonstrate the getChars() method of StringBuffer Class: Example 1:

Java

import java.util.*;

class GFG {

`` public static void main(String[] args)

`` {

`` StringBuffer

`` str

`` = new StringBuffer("Geeks For Geeks");

`` System.out.println("String = "

`` + str.toString());

`` char [] array = new char [ 15 ];

`` Arrays.fill(array, '.' );

`` str.getChars( 0 , 9 , array, 1 );

`` System.out.print(" char array contains : ");

`` for ( int i = 0 ; i < array.length; i++) {

`` System.out.print(array[i] + " ");

`` }

`` }

}

Output:

String = Geeks For Geeks char array contains : . G e e k s F o r . . . . .

Example 2: To demonstrate StringIndexOutOfBoundsException.

Java

import java.util.*;

class GFG {

`` public static void main(String[] args)

`` {

`` StringBuffer

`` str

`` = new StringBuffer("Contribute Geeks");

`` char [] array = new char [ 10 ];

`` Arrays.fill(array, '$' );

`` try {

`` str.getChars( 2 , 1 , array, 0 );

`` }

`` catch (Exception e) {

`` System.out.println("Exception: " + e);

`` }

`` }

}

Output:

Exception: java.lang.StringIndexOutOfBoundsException: srcBegin > srcEnd

References: https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#getChars(int, int, char%5B%5D, int)