• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String variables

 
Rohan Pujari
Greenhorn
Posts: 24
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 637
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Henry Wong
author
Marshal
Pie
Posts: 20829
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Henry
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic