In this guide, we will discuss Java StringBuffer getChars() method with examples.
Syntax of getChars() method
//it will copy the chars from index 1 to 8 //and place it at 3rd index in chArray sb.getChars(1, 8, chArray, 3)
Here, sb
is an object of StringBuffer
class.
getChars() Description
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): This method copies the character sequence of StringBuffer instance from index srcBegin till index srcEnd. It places the copied sequence into destination array dst
starting from index dstBegin
.
To Summarize:
Characters copied from StringBuffer: From srcBegin till srcEnd -1 as srcEnd is exclusive.
Copied characters in destination char array starts from index dstBegin
and end at (dstBegin + (srcEnd -srcBegin - 1))
getChars() Parameters
This method takes four parameters:
- srcBegin: Sequence is copied starting from this index.
- srcEnd: Sequence is copied till this index.
- dst: Destination char array.
- dstBegin: Index in
dst
array, copied sequence placed in dst at this index.
getChars() Return Value
- It does not return anything.
It throws IndexOutOfBoundsException
, if any of the following condition occurs:
- If index
srcBegin
< 0. - If index
dstBegin
< 0. - If
srcBegin
>srcEnd
. - If
srcEnd
>sb.length()
. - If
dstBegin+srcEnd-srcBegin
>dst.length()
.
Example 1
public class JavaExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello World!"); System.out.println("Char Sequence: "+sb); char[] chArray = new char[] {'h', 'i', 'f', 'r', 'i','e','n','d'}; System.out.print("Given char Array: "); System.out.println(chArray); //copy sequence from index 6 to 12 into chArray sb.getChars(6,12,chArray, 2); System.out.print("char Array after copy: "); System.out.println(chArray); } }
Output:
Example 2
public class JavaExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello World!"); System.out.println("Char Sequence: "+sb); char[] chArray = new char[] {'h', 'i'}; System.out.print("Given char Array: "); System.out.println(chArray); //copy sequence from index 6 to 12 into chArray sb.getChars(6,12,chArray, 2); System.out.print("char Array after copy: "); System.out.println(chArray); } }
Output: The destination array size is only 2 so it cannot hold 8 more characters.