-1

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?

yellow
  • 425
  • 7
  • 20
  • 3
    Please provide specific examples instead of making people come up with them for you. – Bill the Lizard Aug 12 '16 at 21:51
  • 1
    Such an assignment would be useless if you have `DataType var = null;` on one line and `var = somethingElse;` on a following line, with no use of `var` in between, since you never use the initial value of the variable. – Andy Turner Aug 12 '16 at 21:53
  • @Andy so why would I be prompted to initialize variable in the first place when I leave it declared. – yellow Aug 12 '16 at 21:55
  • 1
    When you get that error, it's because the compiler has detected a possible code-path where the variable **isn't** initialized (and **is** being used). – Elliott Frisch Aug 12 '16 at 21:56
  • 2
    You need to initialize a local variable before you use it - this is called *definite assignment*. You don't need to initialize the variable when you declare it. It would help if you could show some specific examples. – Andy Turner Aug 12 '16 at 21:56

1 Answers1

0

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.

Little Santi
  • 8,563
  • 2
  • 18
  • 46