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 St
Most often I would say: don't initialize your local variable at all when declaring it, if it would be a dummy value like ""
or null
. Put the real value in, or wait until you can put it in.
The compiler then will make sure that there is at least one assignment before any possible use of the variable. Only for the seldom cases where the compiler isn't smart enough to figure this out (since it needs information not available to it locally) I would use some initialization, and then usually null
is better since it shows with a NullPointerException when I was wrong. (I might add an assert s != null
after the point where I think the Initialization should be done to enforce this.)