Alex Rivera | Logout

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

Asked 2009-08-14T13:51:32.143
50

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?

Edit
Report

1 Answer

1

I think when you use String s = null it will create variable "s" on stack only and no object will exists on heap,but as soon as you declare things as like String s=""; what it will does is like it will create "" object on heap.As we know that Strings are immutable so whenever u wil assign new value to string varible everytime it will create new Object on heap...So I think String s=null is efficient than String s = "";

Suggestions are welcome!!!!!

answered 2011-08-03T13:38:57.707

Your Answer