• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

String and null

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).

 
author
Posts: 23959
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic