• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Null string & empty string

 
Tom Barns
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the difference between null string and Empty string?
please an example.
thanks for your time.
 
Paul Caudle
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tom,
A null String means there is no string object, even...just null. An empty String on the other hand, is a String object simply storing the String: ""
I like to think of it as the difference between nothing (null) and 0 (empty String).

So this would have reference to a null String:
String s1 = null;
(or if at class level String s1).
and this would have reference to an empty String:
String s2 = "";
I hope that helps.
Paul

 
Sean MacLean
author
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a String is declared with no arguments it is considered to be null. The easiest way to thinks of this is by recalling that a String is an object. If the String is 'created' without arguments, then is doesn't point to anything and is, therfore, null.
<PRE>
String myString;
</PRE>

Now, if you create a String that points to an instantiated String object, but that object doesn't contain any characters, then it is consided to be empty.
<PRE>
String myString = "";
</PRE>
The difference is that you now have an reference to an initialized object and can call methods such as myString.length() without getting a NullPointerException.
Hope this clears things up a bit.
Sean
 
Sean MacLean
author
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Sorry Paul - posted at the same time]
 
Paul Caudle
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No Worries, Sean, a different perspective always helps, eh?
 
Tom Barns
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks alot
tom
 
Tom Barns
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks alot
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic