w3resource logo


Introduction to Java Programming

Java String: getChars() Method

Secondary Nav

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

The getChars() method is used to copy characters from a given string into the destination character array.

The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1 (thus the total number of characters to be copied is srcEndsrcBegin).

The characters are copied into the subarray of dst starting at index dstBegin and ending at index:

dstBegin + (srcEnd-srcBegin) - 1

Java Platform: Java SE 8

Syntax :

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

Parameters:

Name Description Type
srcBegin index after the last character in the string to copy. int
srcEnd index of the first character in the string to copy. int
dst the destination array. char
dstBegin the start offset in the destination array. int

Return Value :
Nil

Return Value Type: No type

Throws: IndexOutOfBoundsException - If any of the following is true:

  • srcBegin is negative.
  • srcBegin is greater than srcEnd
  • srcEnd is greater than the length of this string
  • dstBegin is negative
  • dstBegin+(srcEnd-srcBegin) is larger than dst.length

Example : Java String getChars() Method

The following example shows the usage of java String() method.

public class Example {

public static void main(String[] args)
    {
        String str = "This is a sample string.";

        // Copy the contents of the String to a byte array.
        // Only copy characters 4 through 10 from str.
        // Fill the source array starting at position 2.
char[] arr = new char[] { ' ', ' ', ' ', ' ',
                                  ' ', ' ', ' ', ' ' };
str.getChars(4, 10, arr, 2);
System.out.println();
        // Display the contents of the byte array.
System.out.println("The char array equals \"" +
arr + "\"");
System.out.println();
    }
}

Output:

The char array equals "[[email protected]"  

Example of Throws: public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Method

UnsupportedEncodingException - If the named charset is not supported.

Let

str.getChars(-4, 10, arr, 2);

in the above example.

Output:

Exception in thread "main" java.lang.StringIndexOutOfBo
undsException: String index out of range: -4           
        at java.lang.String.getChars(String.java:818)  
        at Example.main(Example.java:12)

Java Code Editor:







Join our Question Answer community to learn and share your programming knowledge.