on line 5, even though sb has nul characters after 12345, 6 is not added at the end of these nul characters, but immediately after 5. so is it replacing the nul character ? what exactly is nul ? when nul is beng counted for the length of the stringbuilder then why isn't it being displayed on line 6 , like how the the blanks are displayed in strings on line 7.
From what I understand null is the absence of a value, but still a value. You can decisively check for null, but you cannot decisively check for the absence of value.
In this case the StringBuilder is set to a length of 10 on line 4, but only the first 5 spaces are used. So you end up with a StringBuilder which is half empty.
On line 5 you append the string "6" to the StringBuilder object, which still has 5 empty (null) spaces.
Maybe if you thought of this like an array:
First create an array and set it equal to "12345789"
Next set the size of the array to 5, thus giving you:
Next set the size of the array to 10, thus giving you:
Finally add an value to the first element in the array that doesn't have a value yet:
The size of the array is still 10, but only the first six elements are used.
Two things of note:
StringBuilder will automatically expand to fit it's capacity, it's the values that you are trying to add exceed it's current capacity and as long as your system has enough RAM/memory.
I'm pretty sure that StringBuilder does use an array in the background.
“The strongest of all warriors are these two — Time and Patience.” ― Leo Tolstoy, War and Peace
The API for StringBuilder's setLength(int newLength) method says:
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.
The null character '\u0000' (Java's default value of a char and the Unicode representation of null) is not a printable character i.e. it is a Unicode character that does not have a written symbol - so you cannot print it via System.out.println('\u0000').
Unicode has a bunch of printable and non-printable characters.
Lilou Laure wrote:so is it replacing the nul character ? what exactly is nul ? when nul is beng counted for the length of the stringbuilder then why isn't it being displayed on line 6 , like how the the blanks are displayed in strings on line 7.
Daniel already provided a very nice explanation about the null character. Have a cow!
Here's a code snippet which actually proves that the 6 is not added immediately after 5Output: 12345-----6