What is the String getChars() method in Java?
The String getChars() method in Java is used to copy the characters of a string into a character array.
Syntax
The getChars() method is declared as shown in the code snippet below:
public void getChars(int srcBeginIndex, int srcEndIndex, char[] dest, int destBeginIndex)
srcBeginIndex: The index of the string’s first character to be copied.srcEndIndex: The index of the last character of the string to be copied.dest: The character array in which the characters of the string will be copied.destBeginIndex: The starting index withindestfrom where characters will be pushed intodest.
Return value
The getChars() method does not return any values.
Note: The
getChars()method throws theIndexOutOfBoundsExceptionif any of the following condition satisties:
srcBeginIndex< 0srcBeginIndex>srcEndIndexsrcEndIndex> string lengthdestBeginIndex< 0destBeginIndex+(srcEndIndex-srcBeginIndex) >destlength
Examples
Example 1
Consider the code snippet below, which demonstrates the use of the getChars() method.
class Main {public static void main( String args[] ) {String str = "Hello World123";char[] dest = new char[12];try {str.getChars(0, 11, dest, 0);System.out.println(dest);}catch (Exception e) {System.out.println("Exception Thrown:" + e);}}}
Explanation
- A string
stris declared in line 3. - A character array
destis declared in line 4. - The
getChars()method is used in line 7 to copy the first 11 characters ofstrindest.
Example 2
Consider another example of the getChars() method in which the IndexOutOfBoundsException is thrown.
class Main {public static void main( String args[] ) {String str = "Hello World123";char[] dest = new char[10];try {str.getChars(0, 11, dest, 0);System.out.println(dest);}catch (Exception e) {System.out.println("Exception Thrown:" + e);}}}
Explanation
- A string
stris declared in line 3. - A character array
destis declared in line 4. - The
getChars()method is used in line 7 to copy the first 11 characters ofstrindest. TheIndexOutOfBoundsExceptionis thrown because the length ofdestis10, which means that no more than ten characters can be copied in it, and thegetChars()method attempts to store11characters in it.