Java String getChars()​ Method Example

1. Overview

In this quick tutorial, We'll learn about String getChars​ method with examples. As well will take a look at internally how getChars​ method implemented and works.

Java String getChars​ Method Example


2. getChars​

This method copies the characters from this string into the destination character array. Also getChars​() method copies only a specified range of characters into new char array.
Source String start index, end index and destination array start index can be configured.

2.1 Syntax

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

This is public method and returns nothing. The passed char array is updated with new values.

2.2 Parameters

srcBegin - index of the first character in the string to copy.
srcEnd - index after the last character in the string to copy.
dst - the destination array.
dstBegin - the start offset in the destination array.

2.3 Throws

This method throws IndexOutOfBoundsException if any one of the following criteria has met.

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

3. Example

Example program on getchars​ method to copy string into char array.

We will copy into array from index 5 to its length.

String srcString = "java-string-api";
char[] destArray = new char[10];

int srcBeiginIndex = 5;
int srcEndIndex = srcString.length();

int destArrayStartInex = 0;

srcString.getChars(srcBeiginIndex, srcEndIndex, destArray, destArrayStartInex);
System.out.println("Input String : "+srcString);
System.out.print("Destination char array contents : ");
for(char c : destArray) {
System.out.print(c);
}

Output:

Input String : java-string-api
Destination char array contents : string-api


4. Internal Implementation

Let us have a look at internal code below.

    public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
checkBoundsBeginEnd(srcBegin, srcEnd, length());
checkBoundsOffCount(dstBegin, srcEnd - srcBegin, dst.length);
if (isLatin1()) {
StringLatin1.getChars(value, srcBegin, srcEnd, dst, dstBegin);
} else {
StringUTF16.getChars(value, srcBegin, srcEnd, dst, dstBegin);
}
}

   
Step 1: Methods checkBoundsBeginEnd() and checkBoundsOffCount() will do input parameters validations. Any one of these "if (srcBegin < 0 || srcBegin > srcEnd || srcEnd > length)" or  "if (dstBegin < 0 || count < 0 || dstBegin > length - count)" is true then will through IndexOutOfBoundsException.


Step 2: If input parameters validation is success then will getChars method based on the Latin or UTF16 char set.

5. Conclusion

in this quick article, how to convert string to char array for a specific range of characters in src string.

getchars​ method is used in internally in toCharArray() method of String class.

Example program is implemented in this article is available on GitHub.

0 Comments