getChars() String Example

getChars() String Example


java.lang.String class comes with many methods to manipulate string. The methods are a boon to Programmers without which would have been a laborious code like C/C++. Present method is getChars() String.

getChars() copies the characters of a sting to a character array. Or, a string can be converted into a character array.

Following is the method signature.

  • public void getChars(int srcStart, int srcEnd, char[] destination, int destinationStart):
    Copies a few characters from the string into the character array destination. Here, a few elements of the existing character array are replaced with the string characters. The part of the string (or a few characters) comprises of all the characters starting from srcStart to srcEnd-1.

    • srcStart: Starting index number of the character in the string from where copying is to be done into the array
    • srcEnd: Ending index number of the character in the string from where copying is to be done into the array
    • destination: It is the character array
    • destinationStart: It is the index number in the array from where copying (better word is replacing) is to start

This method throws StringIndexOutOfBoundsException when srcStart is negative, srcEnd is greater than the string length or destinationStart is negative.

Following example illustrates the usage of the getChars() String method.


getChars() String
Output screen on getChars() String Example

str.getChars(1, 4, carray2, 3);

Starting from character of index number 1 to index number 4 (actual copied are 1 to 4-1) are copied to the elements of character array carray2 starting from index number 3 in the array, That is, carray2 elements of index numbers 3, 4 and 5 are replaced. See the screenshot.

A similar and mostly used method in place of getChars() is toCharArray().

Leave a Reply

Your email address will not be published. Required fields are marked *