If you look at the docs of StringBuilder#setLength(int newLength)
If the newLength argument is greater than or equal to the current length, sufficient null characters ('\u0000') are appended so that length becomes the newLength argument.
That is why when you append "d" after setting the length, it is placed after the 10 null characters.
Q. Why indexOf() doesn't return anything.
It does return a value and that is 10
, since the indexing is 0-based. This is the output of your code.
11 d 10 // the 10 represents the index of d
^-length ^-10 null chars followed by d
The reason you're not getting the output may be because of your console not supporting null
characters. That is why, when it encounters the null character \u0000
, it would just stop printing the values in the console. Try using eclipse which supports printing of Unicode characters.
Sample snapshot: