2

The below code printed different output in different system.

String s = "hello?vsrd".replace('?', '\0');
System.out.println(s);

When I tried in my system (Linux Ubuntu, Netbeans 7.1), it printed :

enter image description here

When I tried the same code in another system (Linux Mint, Netbeans 7.1) it printed as enter image description here

I do understand that \0 acts as a character in java (by referring this answer and obviously s.length() prints 10). And, non-printable characters may be printed like this (box). But, why this behaves only on some systems? is it the difference of jdk version or OSs? I don't want an alternative code, but want to know why exactly it happens so. You can just consider String s = "hello\0vsrd";.

Community
  • 1
  • 1
Visruth
  • 3,430
  • 35
  • 48

2 Answers2

3

\0 is a non-printable character.

Additionally, in C, strings are traditionally terminated with \0, as they don't explicitly store their lengths. Some programs will simply stop printing when they reach that character.

The Netbeans console does print it, but the font might not have a glyph, not even the square, which might explain the different behavior.

Vlad
  • 18,195
  • 4
  • 41
  • 71
0

I know this is not the direct answer. But can be more helpful maybe.
Do you really need '\0'?

Maybe you could use replaceAll().

String s="hello?vsrd".replaceAll("?", "");
qben
  • 813
  • 10
  • 22
  • I know those are alternative ways. I just wanted to know why it happened so. I hope @Vlad answer is right. – Visruth Feb 19 '13 at 14:19