• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can we add null to a String where null is the reference not value ?  RSS feed

 
Deepak Kumar Jena
Ranch Hand
Posts: 71
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On executing the below code adding null (reference) to the String content. Appreciate your comments on the below.



Output
nulla
nullanull

 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The JLS explains this:
JLS wrote:15.18.1. String Concatenation Operator +
If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

JLS wrote:5.1.11. String Conversion
(...)
If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To illustrate what Pawel cited, here is the actual code from the String class


As you can see if the reference is null, the String "null" is returned.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You would probably have to write yourself a utility class with a method to do that specifically if you want different behaviour. Here's a start:-You can probably work out a better name for the method and shou‍ld decide what to do is the left argument is null, too.
 
Junilu Lacar
Sheriff
Posts: 11493
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please clarify what you mean by "null is the reference not value". A few examples of the kind of output that you want instead would be helpful.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!