Java default string if null

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

This makes the initial values of field1 and field2 equal to null. Would it be better to have all my String class fields as follows?

Then, if I’m consistent with class definition I’d avoid a lot of null pointer problems. What are the problems with this approach?

An error can be found when an unexpected «» string is used just as usefully as a raised exception. With the advantage your web app does not crash and embarrass you.

11 Answers 11

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.

+1, but one caveat: if you’re populating your objects from a database, and that database happens to be Oracle, then an empty string is treated as null. However, explicitly initializing to «» isn’t going to help you in that case.

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

  • «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.

Читайте также:  Как удалять из set java

Источник

Оцените статью