Java String getChars() Method
Java String getChars() method copies characters from current String to the destination character array .
Syntax:
public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex)
Parameters:
srcBegin - index of the first character in the string to copy.
srcEnd - index of the last character in the string to copy.
destination - the destination array.
dstBegin - the start offset in the destination array
Return:
It doesn't return any value
Throws:
It throws StringIndexOutOfBoundException 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 destination.length
Java String getChars() Example 1
public class JavaStringGetCharsEx1
{
public static void main(String args[])
{
String str = new String("Welcome to the Tutorial and example");
char[] ch = new char[35];
try{
str.getChars(14, 35, ch, 0);
System.out.println(ch);
}catch(Exception ex){System.out.println(ex);}
}
}
output:
Tutorial and example
Java String getChars() Example 2
public class JavaStringGetCharsEx2
{
public static void main(String args[])
{
String name = "nitish";
char[] c = new char[6];
try{
//retrieving the first character of String
name.getChars(5, 1, c, 0);
System.out.println(c);
}catch(Exception e){
System.out.println(e);
}
}
}
Output:
java.lang.StringIndexOutOfBoundsException: String index out of range: -4
