This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes null or an empty String for Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "null or an empty String for "optional" data members" Watch "null or an empty String for "optional" data members" New topic

null or an empty String for "optional" data members

Salman Ahmed

Joined: Mar 18, 2008
Posts: 27
I have a Java class that models a business domain object. This business domain object has a number of fields that are represented as String-valued data members in the corresponding class. Some of those String-valued fields are not present in some object instances.

Is it better to model such a non-existent (or non-available) field as having an empty String value ("") or should I set it to null?

I've been thinking of this issue in reference to Item #27 from "Effective Java" where Bloch correctly recommends that empty Collections should be returned instead of returning null.

I am just wondering whether the same recommendation should be applicable for simple object types such a String-valued data member.

Would love to hear the thoughts of the more enlightened and experienced minds on JavaRanch...

Amir Alagic
Ranch Hand

Joined: Mar 21, 2006
Posts: 65
I would rather use empty String value (""). Didn't see your code but I guess it can help you to avoid possible NullPointerException(s).

If you, always, use always String instead of null you can in your code just check for String length for your field and don't have to write additional check for null value...
Don't get me started about those stupid light bulbs.
subject: null or an empty String for "optional" data members