benz
benz

Reputation: 4629

String getChars() method confusion

I am reading from K&B about Strings. For some extra know how, i was reading tutorial from Oracle. I am copying the source code from Oracle.

public class StringDemo {  
    public static void main(String[] args) {  
        String palindrome = "Dot saw I was Tod";  
        int len = palindrome.length();  
        char[] tempCharArray = new char[len];  
        char[] charArray = new char[len];  

        // put original string in an   
        // array of chars  
        for (int i = 0; i < len; i++) {  
            tempCharArray[i] =   
                palindrome.charAt(i);  
        }   

        // reverse array of chars  
        for (int j = 0; j < len; j++) {  
            charArray[j] =  
                tempCharArray[len - 1 - j];  
        }  

        String reversePalindrome =  
            new String(charArray);  
        System.out.println(reversePalindrome);  

        //Testing getChars method //1  
        palindrome.getChars(0, len, tempCharArray, 1);  
        String tempString = new String(tempCharArray);  
        System.out.println(tempString);  
    }  
}

I added point-1 in source code. I was understaning getChars method. When i run it, this program give me ArrayIndexOutOfBoundsException. Here is what i read in String docs.

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

Throws: IndexOutOfBoundsException - 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 dst.length

What is the destBegin? What offset, the documentation is talking about. 1 is a valid offset in destination array. Please help me solve this confusion.

Thanks.

Upvotes: 2

Views: 1045

Answers (3)

Mzf
Mzf

Reputation: 5260

As written in the documentation

the characters are copied into the subarray of dst starting at index dstBegin and ending at index:

 dstbegin + (srcEnd-srcBegin) - 1

so in you case is

1 + (len - 0) -1 = len

note that this is the end Index - so your end index is len but in your array the last index is len -1

Upvotes: 1

dganesh2002
dganesh2002

Reputation: 2210

tempCHarArray is of same length as that of palindrome. You are trying to copy the palindrome array starting at index 1. Try this and rerun or start index at 0 ->

char[] tempCharArray = new char[len + 1]; 

Upvotes: 0

rgettman
rgettman

Reputation: 178263

You get an IndexOutOfBoundsException because you have run out of room in the destination array tempCharArray, which is of length len. To copy the array, have getChars start in the destination array at the beginning of the array, at index 0.

palindrome.getChars(0, len, tempCharArray, 0);  

Upvotes: 1

Related Questions