The behavior you see cannot be explained simply by looking at the Java code. Rather, I suspect this is due to what you use to view the output.
First up is:
char[] str = { 'a', 'b', 'c', 0, 'c', 'c', 'f' }; System.out.print(str);
According to javadoc PrintWriter
System.out.print(str);
will be equivalent to calling
System.out.print(str[i]);
for each character. (Yes, everyone, including the null character!). And the write(char) behavior is to simply encode the character according to the default platform encoding and write it. For a null character (zero code point) and a typical 7 or 8 bit encoding that will write the NUL .
On the Java side, there are no funky "zero line-end" facilities with standard Java strings of standard Java I / O classes. Period.
I can think of 3 possible explanations:
You are wrong. Your real code writes something else. (For example, you may have forgotten to recompile ... if you are testing from the command line.)
The strange behavior you see is because your console and / or the utility you use to display the output do something special with NUL characters. (However, I donβt remember hearing a console, etc. Program that handled NUL in such a strange way ...)
Your application has created a custom subtype of PrintWriter that implements some special processing for code zero, and it used System.setOut(...) to redirect output through this class.
Having said that, it's probably a good idea to try to print strings or character arrays containing null characters. The NUL character is the "control code" and is usually classified as non-printable. What you see when you try to print is unpredictable.
If you want to continue this, I suggest redirecting the output of the suspect to a file, and then use some (OS-specific) utility to view the bytes of the file; e.g. od on a Unix / Linux system. I would expect to see null bytes in the file ...
source share