Harish Raj
Harish Raj

Reputation: 27

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

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);
        }
    }
}

Upvotes: 2

Views: 212

Answers (3)

Avnish Kumar Dubey
Avnish Kumar Dubey

Reputation: 1

You are reducing the length while getting the characters. test.getChars(0, test.length() - 1, chars, 0);

Length method:
Returns the length of this string. The length is equal to the number of Unicode code units in the string.

Change it to:

test.getChars(0, test.length(), chars, 0);

Upvotes: 0

pr0f3ss
pr0f3ss

Reputation: 537

A char array is initialized with the value NULL character \u0000. The reason why \u0000 is printed, is because you are only copying test.length()-1 (exclusive stop) to chars and then printing all of chars, which has \u0000 at index test.length()-1.

If you update your code to:

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(), chars, 0);
        for (char temp : chars) {
            System.out.println(temp);
        }
    }
}

it prints:

{
[
]
}
q
w

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1073968

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

Upvotes: 5

Related Questions