Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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: 23956
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
 
What is that? Is that a mongol hoarde? Can we fend them off with this tiny ad?
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic