Java - String getChars() Method
The Java string getChars() method is used to copy characters from this string into the destination character array. The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1 (thus the total number of characters to be copied is srcEnd-srcBegin). The characters are copied into the subarray of dst starting at index dstBegin and ending at index: dstBegin + (srcEnd-srcBegin) - 1.
Syntax
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Parameters
srcBegin |
Specify the index of the first character in the string to copy. |
srcEnd |
Specify the index after the last character in the string to copy. |
dst |
Specify the destination array. |
dstBegin |
Specify the start offset in the destination array. |
Return Value
void type.
Exception
throws IndexOutOfBoundsException, if any of the following is true:
- srcBegin is negative.
- srcBegin is greater than srcEnd.
- srcEnd is greater than the length of this string.
- dstBegin is negative.
- dstBegin+(srcEnd-srcBegin) is larger than dst.length.
Example:
In the below example, getChars() method is used to copy characters from the given string called MyStr into the given character array called MyArr.
public class MyClass { public static void main(String[] args) { String MyStr = "Hello World!"; char MyArr[] = new char[20]; //copy characters from Mystr into MyArr MyStr.getChars(0, 12, MyArr, 0); //print the content of char array System.out.print("MyArr contains:"); for(char c: MyArr) System.out.print(" " + c); } }
The output of the above code will be:
MyArr contains: H e l l o W o r l d !
❮ Java String Methods