H2ONaCl H2ONaCl - 10 months ago 92
Java Question

What if Java prints the NUL character?

public static void main(String[] args) {
char[] array = new char[2];
array[0] = 'a';
String s = new String(array);
assert s.length() == 2;
System.out.print(">" + s + "<\n");
System.out.print(">" + s.substring(1) + "<\n");
System.out.print("end of test.\n");

The output is:

end of test

Unlike C, the Java string is not null character terminated, hence the assertion is true. Why doesn't Java print the
delimiting symbol?

EDIT: Possibly relevant is that this is in Eclipse 4.5.1 on Ubuntu 14.04.


I have tested your code in Eclipse and everything seems to works fine.

However, if I copy/paste the output from Eclipse console and paste it on a text editor it pastes only what you mentioned >a.

I am even pasting this >a copied/pasted from the Eclipse console (when I see >a <... look at my screenshot below).

So, I added this little code snippet to your code:

String f = " >" + s + "<\n";
for (int i=0; i < f.length(); i++) {

And this was the ascii codes:


I think your console has conflict printing the NUL (or 0) character. Additionally, I tested this on Windows so it wouldn't surprise me that Windows has problem copying/pasting strings with NUL in the middle.

This is a screenshot from my eclipse and output: enter image description here