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 :

DataType Parameter Description
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.

package com.javatutorialhq.tutorial;

import java.util.Arrays;

 * This example source code shows the use of getChars method of String class

public class StringGetCharsDemo {

    public static void main(String[] args) {
        String source = "This is a demo";
        char[] target = new char[15];
        target[0] = '*';
        target[1] = '/';
        source.getChars(5,source.length() , target, 2);


Sample Output :

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

string getchars method example

string getchars method example

Exception Scenario :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
	at java.lang.System.arraycopy(Native Method)
	at java.lang.String.getChars(Unknown Source)
	at com.teknoscope.tutorial.StringGetCharsDemo.main(

Suggested Reading List :