aspose file tools*
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 Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String and null" Watch "String and null" New topic
Author

String and null

ronnir paterl
Greenhorn

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

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 - 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).


"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
sscce.org
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String and null