When i am using the null character '\u0000'
, stringbuilder will stop appending new elements.
For example:
StringBuilder _stringBuilder = new StringBuilder();
_stringBuilder.append('\u0000');
_stringBuilder.append('a');
System.out.println("."+_stringBuilder+".");
returns
.
I understand that the null value should not be printed (or printed like if it was a null String value) but in this case, why does stringbuilder is failing to add more elements ?
Note: I am using jdk 1.6.0_38 on ubuntu.
If you append a null value to the StringBuilder object, it would be stored as a “null” (four character string) in the object instead of no value at all.
append. Appends the specified string to this character sequence. The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument. If str is null , then the four characters "null" are appended.
The code creates a StringBuilder object by calling its default (parameterless) constructor. The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters.
If a variable is null then is not referring to anything. So, if you have StringBuilder s = null , that means that s is of type StringBuilder but it is not referring to a StringBuilder instance. If you have a non- null reference then you are free to call methods on the referred object.
The null character is a reserved character that indicates the end of the string, so if you print something followed by \u0000
, nothing else after it will be printed.
Why stringbuilder stops adding elements after using the the null character? It's not really java, it is your terminal that treats \u0000
as the end of the string.
As someone says, with Windows the output can be .a.
(i did not test it), this is because windows terminal works differently than Unix-based systems terminal. I'm pretty sure that if you run this code on a OSX machine you will get the same output as the one you get on linux
Your stringBuilder
still appends the elements, see:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('\u0000');
System.out.println(stringBuilder.length()); // prints 1
stringBuilder.append('a');
System.out.println(stringBuilder.length()); // prints 2
My guess is that your console stops printing after the \u0000
termination character. A different console might handle that differently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With