• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

When to Null, and when to not

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just a quick thank you and comment that information sometimes is useful years later. I used the following tonight in my assignment:

From Marilyn, 5/19/2001:

A null String doesn't really exist. It is only a reference to a spot that may eventually hold a String. It really is a "place holder".

An empty String, on the other hand, is an actual String of zero length (no characters).

If you are never going to use that String (as in a placeholder in an array), use a null. If there's a chance that String will print, you need to initialize that String to "" or "abc" or whatever.
 
Sheriff
Posts: 1367
18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the 'Head First Java' book by Kathy Sierra and Bert Bates they describe variables that are references to objects (such as String objects, Person objects, Game objects, as opposed to primitive types) as remote controls that can be programmed to point at any object of the corresponding kind. A null reference is a remote control that exists, but hasn't been programmed.

With the variable that points to an empty String ( "" ) you have an actual String object living somewhere on the heap, and the remote control, and the remote has been programmed to access that String object. With the null reference, no String object on the heap, and no programming the remote.

Before I read about it in this way I was very, very confused.
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're welcome, Mark.

I think Kathy and Bert do a great job of explaining things in ways that nobody has done before.
 
Would you like to try a free sample? Today we are featuring tiny ads:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic