This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes String and null Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String and null" Watch "String and null" New topic

String and null

ronnir paterl

Joined: Oct 18, 2007
Posts: 11
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;

Why is null considered to be a sting here?

Thank You
marc weber

Joined: Aug 31, 2004
Posts: 11343

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 - String Conversion...
If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Henry Wong

Joined: Sep 28, 2004
Posts: 18509

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.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
I agree. Here's the link:
subject: String and null
Similar Threads
Difference between NULL and empty string
Confusing contructor call
why this?
Simple Q on Strings
why complie time error?