Friday, October 24, 2025
HomeLanguagesJavaJava String getChars() with examples

Java String getChars() with examples

The java string getChars() method copies characters from the given string into the destination character array.
Syntax: 
 

public void getChars(int srhStartIndex, 
int srhEndIndex, char[] destArray, int destStartIndex)     
Parameters:
srhStartIndex : Index of the first character in the string to copy. 
srhEndIndex : Index after the last character in the string to copy.
destArray : Destination array where chars will get copied.
destStartIndex : Index in the array starting from where the chars
                 will be pushed into the array.
Return: It does not return any value.

Exception: StringIndexOutOfBoundsException – If srhStartIndex, srhEndIndex are not in proper range.
Example : To show working of getChars() method 
 

java




// Java program to demonstrate
// working of getChars() method
 
class Gfg1 {
    public static void main(String args[])
    {
        String str = "Welcome! to Lazyroar";
 
        char[] destArray = new char[20];
        try {
            str.getChars(12, 25, destArray, 0);
            System.out.println(destArray);
        }
        catch (Exception ex) {
            System.out.println(ex);
        }
    }
}


Output: 
 

Lazyroar

 

java




// Java program to demonstrate
// exception condition in
// working of getChars() method
 
class Gfg2 {
    public static void main(String args[])
    {
        String str = "Welcome! to Lazyroar";
 
        char[] destArray = new char[20];
        try {
            // Starting index 0 and ending index 24
            str.getChars(12, 26, destArray, 0);
            System.out.println(destArray);
        }
        catch (Exception ex) {
            System.out.println(ex);
        }
    }
}


Output: 
 

java.lang.StringIndexOutOfBoundsException: String index out of range: 26

 

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS