Should I set the initial java String values from null to ""?

That way lies madness (usually). If you're running into a lot of null pointer problems, that's because you're trying to use them before actually populating them. Those null pointer problems are loud obnoxious warning sirens telling you where that use is, allowing you to then go in and fix the problem. If you just initially set them to empty, then you'll be risking using them instead of what you were actually expecting there.


Absolutely not. An empty string and a null string are entirely different things and you should not confuse them.

To explain further:

  • "null" means "I haven't initialized this variable, or it has no value"
  • "empty string" means "I know what the value is, it's empty".

As Yuliy already mentioned, if you're seeing a lot of null pointer exceptions, it's because you are expecting things to have values when they don't, or you're being sloppy about initializing things before you use them. In either case, you should take the time to program properly - make sure things that should have values have those values, and make sure that if you're accessing the values of things that might not have value, that you take that into account.


Does it actually make sense in a specific case for the value to be used before it is set somewhere else, and to behave as an empty String in that case? i.e. is an empty string actually a correct default value, and does it make sense to have a default value at all?

If the answer is yes, setting it to "" in the declaration is the right thing to do. If not, it's a recipe for making bugs harder to find and diagnose.


I disagree with the other posters. Using the empty string is acceptable. I prefer to use it whenever possible.

In the great majority of cases, a null String and an empty String represent the exact same thing - unknown data. Whether you represent that with a null or an empty String is a matter of choice.


Generally it would be best to avoid this. A couple of reasons:

  1. Getting a NullPointerException is generally a good warning that you are using a variable before you should be, or that you forgot to set it. Setting it to an empty string would get rid of the NullPointerException, but would likely cause a different (and harder to track down) bug further down the line in your program.

  2. There can be a valid difference between null and "". A null value usually indicates that no value was set or the value is unknown. An empty string indicates that it was deliberately set to be empty. Depending on your program, that subtle difference could be important.