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 within dest from where characters will be pushed into dest.

Return value

The getChars() method does not return any values.

Note: The getChars() method throws the IndexOutOfBoundsException if any of the following condition satisties:

  • srcBeginIndex < 0
  • srcBeginIndex > srcEndIndex
  • srcEndIndex > string length
  • destBeginIndex < 0
  • destBeginIndex+(srcEndIndex-srcBeginIndex) > dest length

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 str is declared in line 3.
  • A character array dest is declared in line 4.
  • The getChars() method is used in line 7 to copy the first 11 characters of str in dest.

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 str is declared in line 3.
  • A character array dest is declared in line 4.
  • The 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.

Free Resources