Java String getChars()
The Java String class getChars() method copies the content of this string into a specified char array. There are four arguments passed in the getChars() method. The signature of the getChars() method is given below:
Signature
Parameters
int srcBeginIndex: The index from where copying of characters is started.
int srcEndIndex: The index which is next to the last character that is getting copied.
Char[] destination: The char array where characters from the string that invokes the getChars() method is getting copied.
int dstEndIndex: It shows the position in the destination array from where the characters from the string will be pushed.
Returns
It doesn’t return any value.
Exception Throws
The method throws StringIndexOutOfBoundsException when any one or more than one of the following conditions holds true.
- If srcBeginIndex is less than zero.
- If srcBeginIndex is greater than srcEndIndex.
- If srcEndIndex is greater than the size of the string that invokes the method
- If dstEndIndex is is less than zero.
- If dstEndIndex + (srcEndIndex – srcBeginIndex) is greater than the size of the destination array.
Internal implementation
The signature or syntax of string getChars() method is given below:
Java String getChars() Method Example
FileName: StringGetCharsExample.java
Output:
tutoraspire
Java String getChars() Method Example 2
The method throws an exception if index value exceeds array range. Let’s see an example.
FileName: StringGetCharsExample2.java
Output:
java.lang.StringIndexOutOfBoundsException: offset 10, count 14, length 20
Java String getChars() Method Example 3
The getChars() method does not copy anything into the char array, provided the value of srcBeginIndex and srcEndIndex are the same. It is because the getChars() method copies from the srcBeginIndex index to srcEndIndex – 1 index. As srcBeginIndex is equal to srcEndIndex; therefore, srcEndIndex – 1 is less than srcBeginIndex. Therefore, the getChars() method copies nothing. The following example confirms the same.
FileName: StringGetCharsExample3.java
Output:
The getChars() method prints nothing as start and end indices are equal.