yellow yellow - 3 months ago 18
Java Question

Initialization of variable java

Say I have a variable of some type var. At times when I don't initialize the variable I am asked to initialize( by eclipse) say to null. At times when I initialize at very beginning it says

DataType var= null;
"Remove this useless assignment to local variable "var""
.

My question is why is this difference in initialization at different scenarios? Is it datatype dependent?

Answer

In the first place, generally it is not a good practice initializing to null, because the compiler is warning you about a variable that is being read without being properly initialized. And setting it to null is very dubiously a proper initialization; Most probably it will produce a NullPointerException if being de-referenced.

I encourage you to follow always these rules whith initialization of local variables:

  • Set an initial value (and only once) as soon as it is available. If necessary, delay the declaration to the point where a valid value is available.
  • Do not initialize to null unless you write the subsequent code to be aware of that situation.

To end, if Eclipse warns you about a "useless initialization" is surely because the initial value you set to the variable (even if it was null) is never read before the next value is set.