Way2Java

getChars() String Example

java.lang.String class comes with many methods to manipulate string. The methods are a boon to Programmers without which would have been a laborious code like C/C++. Present method is getChars() String.

getChars() copies the characters of a sting to a character array. Or, a string can be converted into a character array.

Following is the method signature.

This method throws StringIndexOutOfBoundsException when srcStart is negative, srcEnd is greater than the string length or destinationStart is negative.

Following example illustrates the usage of the getChars() String method.

public class StringMethodDemo
{
 public static void main(String args[])
 {
  String str = "ABCDEFGHI";
  char carray1[] = new char[str.length()];
   
  System.out.println("To convert whole string into character array and printing array elements:");
  str.getChars(0, str.length(), carray1, 0); 
  for(int i = 0; i < carray1.length; i++)
  {
   System.out.print(carray1[i] + ", ");
  }

  System.out.println("\n\nTo copy a part of string into character array and printing array elements:");
  char carray2[] = { 'a', 'b', 'c',  'd',  'e',  'f',  'g',  'h'  };
  str.getChars(1, 4, carray2, 3); 
  for(int i = 0; i < carray2.length; i++)
  {
   System.out.print(carray2[i] + ", ");
  }
 }
}



Output screen on getChars() String Example

str.getChars(1, 4, carray2, 3);

Starting from character of index number 1 to index number 4 (actual copied are 1 to 4-1) are copied to the elements of character array carray2 starting from index number 3 in the array, That is, carray2 elements of index numbers 3, 4 and 5 are replaced. See the screenshot.

A similar and mostly used method in place of getChars() is toCharArray().