The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
October 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Sting Theory

Posted by Matt Gerrans on October 31, 2001 at 12:51 AM


> Quick question. Are the following lines equivalent?
> (1) String p = new String();
> (2) String p = null;
> (3) String p = "";
> If they are not all equivalent, which ones are? Or are they all different? If so, what does each one print out? I'm asking cause at times I need to print a string that contains null (if a certain condition is not met, otherwise the string contains stuff). Thnx in advance!
> Hiran

No, they are not equivalent. The first and the third point to a valid empty string, but not the same one. The first is really not recommended; since Strings are immutable, you may as well have all your references to empty strings point to the same empty string, which is what you get if you always use case 3. Case 2, is the same as String p; Which is to say, you don't need the = null part, since that is what happens if you don't initialize it, anyway. By the way, if you are using case 2, then you will have code that looks like this:


if( p != null )
{
// Do something really clever and intersting with the
// String referred to by p.
}
else
{
// need to do something that creates a string object
// for p to refer to, before it is useful.
}

On the other hand, if you are using something like case 3, then your code would look more like this:


if( p.length() > 0 )
{
// Do something really clever and intersting with the
// String referred to by p.
}
else
{
// Do something really intesting with the empty String
// referred to by p, or refer it to a more interesting
// instance of a String object and proceed.
}

To summarize the three:


  1. There is almost no reason to use the first case (the only one is if, for some zany reason, you need a new unique empty String).
  2. The second case sounds like what you want (sounds like you want an unitialized String), but you don't need to explicitly initialize it to null, since that is the default behavior.
  3. The Third case is the most common and allows the JVM to share the identical String objects (if you create many variables this way, they all point to the same empty string), which means better performance and memory usage. This also holds true for String that are not empty.

By the way, here's how you get a string that contains null:
String nuthin = "null";
Just kidding. Nerd joke. Sorry.

- mfg



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us