In this guide, we will discuss Java StringBuilder getChars() method with examples.
Syntax of getChars() method:
//it will copy the sb char sequence from 1 to 5 //and paste it at 3rd index in chArray sb.getChars(1, 5, chArray, 3)
Here, sb is an object of StringBuilder class.
Also read: StringBuilder in Java
getChars() Description
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): This method copies the character sequence of StringBuilder 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 StringBuilder: 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: Integer value that represents the start index. Copy starts from this index.
- srcEnd: Integer value that represents the end index. Copy ends at this index. This is exclusive, which means the char present at this index is not copied.
- 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) { StringBuilder sb = new StringBuilder("Hello World"); System.out.println("Char Sequence: "+sb); char[] chArray = new char[] {'h', 'i', 'f', 'r', 'i','e','n','d','s'}; System.out.print("Given char Array: "); System.out.println(chArray); //copy sequence from index 6 to 11 into chArray sb.getChars(6,11,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) { StringBuilder sb = new StringBuilder("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 11 into chArray sb.getChars(6,11,chArray, 2); System.out.print("char Array after copy: "); System.out.println(chArray); } }
Output: The destination array size is only 2. It cannot hold 7 characters so exception occurred.