0

I am comparing the following two lines of code and their output:

System.out.print("x = "+'\u0000');

output: x =

System.out.print("x = "+null);

output: x = null

We know that in unicode system '\u0000' is null so how does it print as the string "", while null is printed as "null"?

Ishan
  • 1,172
  • 10
  • 25
  • @kocko, this is potentially a bad choice of duplicate. The actual duplicate is more likely to be [Concatenating null strings in Java](http://stackoverflow.com/questions/4260723/concatenating-null-strings-in-java) as the question here is "why does the string concatenation operator write `null` for null and `""` for `'\0000'`"? – Andy Brown Aug 06 '15 at 08:37
  • @Andy Brown - thanks – Ishan Aug 06 '15 at 08:58

1 Answers1

0

null is not a character. You can use it for object references without a value. \u0000 is a literal for new Character(0). It is an instance of a class, while null is not.

So the toString() Method of a Character instance returns the character as it should be displayed. null doesn't have a toString(), String.valueOf(null) is called instead which returns "null".

G_hi3
  • 588
  • 5
  • 22
  • While valid, this doesn't answer the original question about why `System.out.print("x = "+null);` prints `x = null`, and `System.out.print("x = "+'\u0000');` prints `x = ` – Andy Brown Aug 06 '15 at 08:49