java.lang.String getChars()

Description :

This java tutorial shows how to use the getChars() method of java.lang.String class. This method returns void. The getChars() method of String class generally copies character from this string to the target character array object.

Method Syntax :

public void getChars(int srcBegin,int srcEnd,char[] dst,int dstBegin)

Parameter Input :

int|srcBegin|the starting index of the source String to be copied to the char array
int|srcEnd|the end index of the source String to be be copied to the target char array
char[]|dst|the target char array
int|dstBegin|char offset on the target char array

Method Returns :

This method returns void.

Exception :


The getChars() method of String class throws this exception whenever the following condition is met:

  • srcBegin and srcEnd is negative
  • srcBegin is greater than the srcEnd
  • srcEnd is greater than the length of this string. Max value expected is String length
  • destBegin is negative
  • the length to be copied + dstBegin is greater than to the size of the targetarray (dst.length)

Java Code Example :

This example source code demonstrates the use of getchars() method of String class. The example also made use of the length() method of String class which generally get how many characters the source string is. The length has been used as the srcEnd parameter which means we are getting the characters starting from the srcBegin up to the end of the source String. We have also instantiated a new character array for the target char as parameter of our getChars() method.

Sample Output :

Running the getChars() example source code will give you the following output

string getchars method example

string getchars method example

Exception Scenario :

Suggested Reading List :