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.

  • public void getChars(int srcStart, int srcEnd, char[] destination, int destinationStart):
    Copies a few characters from the string into the character array destination. Here, a few elements of the existing character array are replaced with the string characters. The part of the string (or a few characters) comprises of all the characters starting from srcStart to srcEnd-1.

    • srcStart: Starting index number of the character in the string from where copying is to be done into the array
    • srcEnd: Ending index number of the character in the string from where copying is to be done into the array
    • destination: It is the character array
    • destinationStart: It is the index number in the array from where copying (better word is replacing) is to start

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] + ", ");
  }
 }
}


getChars() String
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().

Leave a Comment

Your email address will not be published.