سؤال

    StringBuilder builder = new StringBuilder();
    builder.setLength(10);
    builder.append("d");        
    System.out.println(builder.length() + "\t" + builder.toString() + "\t" + builder.indexOf("d"));

Output:

11 

Problem:

Why indexOf() doesn't return anything.

My Understanding:

 As per my understanding, it should return 10, since StringBuilder is counting the "d" as part of its length in length().
 But in case if "d" is not part of string hold by StringBuilder then, it should return -1 and length should be 10.
هل كانت مفيدة؟

المحلول

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:

Output Snapshot

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top