Java.lang.String.getChars() Method

Advertisements


Description

The java.lang.String.getChars() method copies characters from this 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 i.e. the total number of characters to be copied is srcEnd-srcBegin.

The characters are copied into the subarray of dst starting at index dstBegin and ending at index: dstbegin + (srcEnd-srcBegin) - 1

Declaration

Following is the declaration for java.lang.String.getChars() method

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

Parameters

  • srcBegin -- This is the index of the first character in the string to copy.

  • srcEnd -- This is the index after the last character in the string to copy.

  • dst -- This is the destination array.

  • dstBegin -- This is the start offset in the destination array.

Return Value

This method does not return any value.

Exception

  • IndexOutOfBoundsException -- It throws this exception 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

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

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

  public static void main(String[] args) {
  
    String str = "Website:www.tutorialspoint.com";
    System.out.println(str);
    
    // character array
    char[] chararr = new char[30];
   
    /* copies characters from starting and ending index into the destination 
    character array */
    str.getChars(12, 26, chararr, 0);

    // print the character array
    System.out.print("Value of character array : ");
    System.out.println(chararr);
  }
}

Let us compile and run the above program, this will produce the following result:

Website:www.tutorialspoint.com
Value of character array : tutorialspoint



Advertisements
Advertisements