Java String getChars() Method

In this tutorial, we will learn about Java String getChars() Method.

Sometimes we may need to copy the characters in the String to an array in Java. The String class in Java provides a method getChars(). The String getChars() method is used to copy String characters into the destination character Array.


The syntax of String getChars() method is:

where, srcBegin – index of the first character in the string to copy.
srcEnd – index after the last character in the string to copy.
dest – the destination array.
destBegin – the start offset in the destination array.

The getChars() method throws:

IndexOutOfBoundsException – In following situations.

  • srcBegin is -ve.
  • srcBegin is > srcEnd.
  • srcEnd is > the length of this string.
  • dstBegin is -ve.
  • dstBegin+(srcEnd-srcBegin) is larger than dest.length.




Here we have taken a String “This is a getChars() method demo.” in str and applied getChars() method to get an array of characters in the chArray. If you observe the output, we have printed the content of the array and it contains the characters from 5 to 15 in the String.

What if we mention the array size less than the no. of characters copied in the array using getChars() method ?

This will throw ArrayIndexOutOfBoundsException. Let’s see this with an example.



You can also learn about String length() method at Java String length() Method.