Java String getChars()

The java string getChars() method copies the content of this string into specified char array. There are 4 arguments passed in getChars() method.

Internal implementation
void getChars(char dst[], int dstBegin) { System.arraycopy(value, 0, dst, dstBegin, value.length); }

The method getChars() is used for copying String characters to an Array of chars.

public void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin)
Parameters description:
  • srcBegin – index of the first character in the string to copy.

  • srcEnd – index after the last character in the string to copy.

  • dest – Destination array of characters in which the characters from String gets copied.

  • destBegin – The index in Array starting from where the chars will be pushed into the Array.

It throws IndexOutOfBoundsException – If any of the following conditions occurs:

(srcBegin<0) srcBegin is less than zero. (srcBegin>srcEnd) srcBegin is greater than srcEnd.

(srcEnd > length of string) srcEnd is greater than the length of this string.

(destBegin<0) destBegin is negative.

dstBegin+(srcEnd-srcBegin) is larger than dest.length.


It doesn't return any value.


It throws StringIndexOutOfBoundsException if beginIndex is greater than endIndex.

Example: getChars() method
public class Test { public static void main(String args[]) { String str = new String("This is a String Handling Tutorial"); char[] array = new char[6]; str.getChars(10, 16, array, 0); System.out.println("Array Content:" ); for(char temp: array){ System.out.print(temp); } char[] array2 = new char[]{'a','a','a','a','a','a','a','a'}; str.getChars(10, 16, array2, 2); System.out.println("Second Array Content:" ); for(char temp: array2) { System.out.print(temp); } } }

Array Content: StringSecond Array Content: aaString
Java String getChars() method example
public class Test { public static void main(String args[]) { String str = new String("hello cprogramcoding what are u doing"); char[] ch = new char[30]; try{ str.getChars(6, 20, ch, 0); System.out.println(ch); }catch(Exception ex){System.out.println(ex);} } }

Java String getChars() Method Example

It throws an exception if index value exceeds array range.

public class Test { public static void main(String[] args) { String str = new String("Welcome to cprogramcoding"); char[] ch = new char[30]; try { str.getChars(0, 19, ch, 0); System.out.println(ch); } catch (Exception e) { System.out.println(e); } } }

Welcome to cprogram