Often I have a class as such:
public class Foo { private String field1; private String field2; // etc etc etc }
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?
public class Foo { private String field1 = ""; private String field2 = ""; // etc etc etc }
Then, if I'm consistent with class definition I'd avoid a lot of null pointer problems. What are the problems with this approach?
String Declaration Only See, member variables are initialized with a default value when the class is constructed, null in String's case.
In java, a String is initialized in multiple ways. Either by using constructor or by using Literal. There is a difference in initializing String by using a new keyword & using Literal. Initializing String using new keywords every time create a new java object.
The default constructor initializes the string to the empty string. This is the more economic way of saying the same thing. However, the comparison to NULL stinks. That is an older syntax still in common use that means something else; a null pointer.
out. println(monthString); In order to use a local variable in java it must be initialized to something even if that something is setting it equal to null .
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With