Last character of a char array created from String's getchars() method changes to different character

Harish Raj :

I was working with getchars() method. Code didn't work as I expected, after debugging I found that last character added to char array from getchars() method gets changed. Last character value is changed to '\u0000' instead of 'w' from string passed. Debugged Values attached here

public class TestDS {
    public static void main(String[] args) throws Exception {
        String test = "{[]}qw";
        char[] chars = new char[test.length()];
        test.getChars(0, test.length() - 1, chars, 0);
        for (char temp : chars) {
            System.out.println(temp);
        }
    }
}
T.J. Crowder :

You're not copying the last character. The end index is an index, so it should point just past the end of the string. As it says in the JavaDoc:

srcEnd - index after the last character in the string to copy.

(my emphasis)

So you don't want the - 1 after test.length(). You're seeing the default value of chars[chars.length-1], which is 0 (because arrays are initialized to all-bits-off values).

So:

test.getChars(0, test.length(), chars, 0);
// ---------------------------^

To illustrate:

{[]}qw
^     ^
|     |
|     +−−− srcEnd
+−−−−−−−−− srcBegin

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=140192&siteId=1