Reputation: 3091
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.
Upvotes: 12
Views: 2415
Reputation: 22233
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
Upvotes: 7
Reputation: 26185
I tried your test, and it does not fail in Eclipse on my Windows 7 system. However, running this test program will distinguish between non-appending and non-printing. I suggest running it in the failing environment.
public class Test {
public static void main(String[] args){
StringBuilder _stringBuilder = new StringBuilder();
_stringBuilder.append('\u0000');
_stringBuilder.append('a');
System.out.println("."+_stringBuilder+".");
System.out.println(_stringBuilder.length());
System.out.println(_stringBuilder.charAt(1));
}
}
If the problem is non-appending, the length will be less than 2, and the attempt to print the character at index 1 will fail. If the problem is non-printing, the length will be 2 and the character at index 1 will be 'a'.
I think that non-printing is much more likely than non-appending.
Upvotes: 1
Reputation: 37813
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.
Upvotes: 7