Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does System.out.println() terminate at ASCII Code zero

Tags:

java

Try this piece of code -

public class WhitespaceTest
{
    public static void main(String[] args)
    {
        int x = 0;
        char c = (char) x;
        System.out.println("c-->"+c+"<---this doesn't print?");
    }
}

The output is -

c-->

Why does System.out.println() terminate at ASCII code zero?

I tried this in JCreator LE under Windows 7.

like image 854
CodeBlue Avatar asked Jun 18 '12 15:06

CodeBlue


2 Answers

It depends on what your console does (or whatever else is handling System.out). System.out will propagate all the information just fine, and if your console attaches no particular meaning to U+0000 then all will be well. However, many UI controls will treat that as a terminating character. This isn't Java's "fault" - it's the UI control itself.

(Just for reference, running that code within a Windows command prompt on Windows 7 is fine for me.)

like image 188
Jon Skeet Avatar answered Sep 21 '22 15:09

Jon Skeet


In C/C++ style strings the end of the string is determined by the location of the terminating null-character (the character with value 0, like in your case). Most likely the System.out.println() call passes the string to the OS verbatim, which thinks the string ended at the null-character, and only prints up to that point

like image 28
Attila Avatar answered Sep 18 '22 15:09

Attila