Java: String getChars() method

In this article, we will discuss how to convert String into character array using String’s getChars() method

 

getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) method: This String method is used to copy string into destination character array

Parameters:

  • srcBegin      –> index of the 1st character in the string to copy
  • srcEnd         –> index after the last character in the string to copy (i.e.; srcEnd-1)
  • dst[]            –> the destination array
  • dstBegin      –> the start offset in the destination array

 

Method Signature:

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

 

Returns:

  • Return type of this method void,
  • but copies from invoking string into destination character array (provided in the method signature/prototype)

 

Throws:

IndexOutOfBoundException: throws this exception for following cases,

  • srcBegin < 0 i.e.; srcBegin is negative
  • srcBegin > srcEnd
  • srcEnd > length of the invoking string
  • dstBegin is negative i.e.; dstBegin < 0
  • dstBegin+(srcEnd-srcBegin) is larger than dst.length

 

Examples on getChars() method:

Sample Java program to convert string into character array & finally copying the conversion into destination character array

StringGetCharsMethod.java

package in.bench.resources.string.methods;

public class StringGetCharsMethod {

	public static void main(String[] args) {

		// sample string literal
		String srcString = "BenchResources.Net has lot of Java tutorials";
		System.out.println("Sample string : " + srcString);

		// target character array
		char[] targetCharArr = new char[14];

		// copy from(start, end) index of src string into dest char array
		srcString.getChars(30, 44, targetCharArr, 0);

		// printing to console
		System.out.print("\nValue inside character array : " );
		System.out.println(targetCharArr);
	}
}

Output:

Sample string : BenchResources.Net has lot of Java tutorials

Value inside character array : Java tutorials

 

References:

https://docs.oracle.com/javase/tutorial/java/data/strings.html
https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html

 

Happy Coding !!
Happy Learning !!