The String getChars()
method in Java is used to copy the characters of a string into a character array.
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 within dest
from where characters will be pushed into dest
.The getChars()
method does not return any values.
Note: The
getChars()
method throws theIndexOutOfBoundsException
if any of the following condition satisties:
srcBeginIndex
< 0srcBeginIndex
>srcEndIndex
srcEndIndex
> string lengthdestBeginIndex
< 0destBeginIndex
+(srcEndIndex
-srcBeginIndex
) >dest
length
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);}}}
str
is declared in line 3.dest
is declared in line 4.getChars()
method is used in line 7 to copy the first 11 characters of str
in dest
.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);}}}
str
is declared in line 3.dest
is declared in line 4.getChars()
method is used in line 7 to copy the first 11 characters of str
in dest
. The IndexOutOfBoundsException
is thrown because the length of dest
is 10
, which means that no more than ten characters can be copied in it, and the getChars()
method attempts to store 11
characters in it.