Java String getChars() Method Example

If you need to extract more than one character at a time, you can use the getChars() method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. Thus, the substring contains the characters from sourceStart through sourceEnd–1.

The array that will receive the characters is specified by target. The index within the target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring.

Java String getChars() Method Example

The following program demonstrates  getChars():
class getCharsDemo {
    public static void main(String args[]) {
        String s = "This is a demo of the getChars method.";
        int start = 10;
        int end = 14;
        char buf[] = new char[end - start];
        s.getChars(start, end, buf, 0);

Here is the output of this program: