• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String and null

 
ronnir paterl
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
I'm a bit confused about null. As i understand, null is a reserved keyword, represents a void reference and doesn't have a value.

Here's my question. why does this code fragment give output as "nullhi".

String abc = null;
abc+="hi";
System.out.println(abc);


Why is null considered to be a sting here?



Thank You
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JLS - 15.18.1 String Concatenation Operator +...
If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time.

JLS - 15.18.1.1 String Conversion...
If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
 
Henry Wong
author
Marshal
Pie
Posts: 21003
77
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The key is this line of code:



This is syntactic sugar. The compiler will create a string buffer/builder, append the null (abc reference), append the "hi" string, and assign the resultant string to the abc reference.

A string buffer/builder will convert a null reference to the "null" string, when you try to append it.

Henry
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic