Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 287
Martlark Avatar asked Aug 14 '09 13:08

Martlark


People also ask

Is Java string initialized to null?

String Declaration Only See, member variables are initialized with a default value when the class is constructed, null in String's case.

What is the best way to initialize string in Java?

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.

Can we initialize string with null?

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.

Does string need to be initialized Java?

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 .


2 Answers

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.

like image 117
Yuliy Avatar answered Oct 16 '22 00:10

Yuliy


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.

like image 22
Paul Tomblin Avatar answered Oct 16 '22 00:10

Paul Tomblin