Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why stringbuilder stops adding elements after using the null character?

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.

like image 958
VirtualTroll Avatar asked Jul 03 '13 13:07

VirtualTroll


People also ask

What happens if you pass null to StringBuilder?

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.

Can StringBuilder append null?

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.

How many characters can StringBuilder hold?

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.

How check StringBuilder is null?

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.


2 Answers

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

like image 74
BackSlash Avatar answered Oct 20 '22 10:10

BackSlash


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.

like image 7
jlordo Avatar answered Oct 20 '22 09:10

jlordo