Your textbook is wrong! Writing such code is pointless and a waste of time typing it, and the computers that run it.
As others have said, the compiler ensures that variables outside the methods (class / instance variables) are set to 0, false, or null. Since you probably know that the compiler does not give variables inside the values of the methods, but instead forces you to give them a value before using them.
You will find, if you do something “correctly,” that about 90% -95% of your “variables” never change after they are assigned a value. However, new programmers tend to do such things:
int x = 0;
this does not allow you to mark x as "final". If you can mark x as "final" then this will prevent the value from being accidentally modified, which prevents errors.
I would write code like:
final int x;
This is called an empty ending (a finite variable that does not matter when declared).
If you remember that class / instance variables are initialized by the runtime, you hopefully will not write code to initialize them by dropping values, and then you can mark them as final.
My personal practice is to always mark everything as final until I find that I need to modify it and never initialize the variable until I know the actual value that I want to have. This makes the code faster (not noticeable, since assignments are usually very fast) and safer, as I rarely accidentally change the value when I shouldn't.
TofuBeer Oct 08 2018-10-10 19:43
source share