Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Java String method (local) variables be initialized to null or ""?

Tags:

java

string

What is the best practice for initializing a String method (local) variable to avoid the "Variable might not have been initialized" error in Java?

String s=null; or String s="";

Does it make a difference? If so, which one is better and why?

I've read conflicting answers on the web.

Thanks!

like image 792
Canam Avatar asked Mar 29 '11 21:03

Canam


2 Answers

Yes, it makes a difference. One is a reference to an empty string, one is a null reference. They're not the same.

Which is better? It depends whether you want a null value or a reference to an empty string... they behave differently, so pick the one which behaves the way you want it to.

I rarely need to assign a "dummy" value to a variable though - usually just initializing the variable at the point of declaration with the real value I want is fine. If you can give us more context, we may be able to help you structure your code better so this isn't a problem for you.

like image 95
Jon Skeet Avatar answered Oct 18 '22 10:10

Jon Skeet


Best practice is to make as many fields final as possible or use default values to avoid clients instantiating bad or incomplete objects. If it makes sense for the field to be an empty string by default (i.e. it will not risk logic errors) then by all means do it that way. Otherwise, at least null will throw an exception when a client invokes a method on an object that hasn't been properly instantiated.

So in general, try to force client code to create complete objects during construction. If you don't know what the string should be at construction time, then have them pass it in as a parameter. If the string is just used for internal logic, it may be better as a local variable or parameter - and in that case I generally prefer null to "" because == null is more explicit than isEmpty().

like image 37
Garrett Hall Avatar answered Oct 18 '22 08:10

Garrett Hall