It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String variables" Watch "String variables" New topic

String variables

Rohan Pujari

Joined: Feb 27, 2007
Posts: 24
when we declare a string variable as
String s = null
then the string referrence variable s does not refer to any String object.
How does the statement s+=s
produce a value of nullnull??
does this mean that when s does not refer to any string object it gets a value of null. but still any other operations on the variable using the dot operator results in nullpointerexception.
Stuart Ash
Ranch Hand

Joined: Oct 07, 2005
Posts: 637
A null-pointing String reference when asked to cough up its String value with the + op, returns the literal 'null'. When any method is invoked though, there has to be a valid object to the ref.

ASCII silly question, Get a silly ANSI.
Henry Wong

Joined: Sep 28, 2004
Posts: 20521

This is actually related to the StringBuffer (StringBuilder) class. Normally, when you try to append an object to the string buffer, it will use the toString() method to get the string to append. However, if the object in question is not available (null), the append() method will append the string value of "null".

How is this related? The adding of strings are actually syntactic sugar for append() method calls to string buffers.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
I agree. Here's the link:
subject: String variables
It's not a secret anymore!