I was given a link to the official oracle documentation: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
where it is said:
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
I want to emphasis this part:
Relying on such default values, however, is generally considered bad programming style.
But, oh boy, this is, I would say, a fundamental part of the language specification knowing that instance variables have default values. Why on earth this is a bad programming practice if it is widely used even in Java SE libraries source code?
In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables aren't given a default value. You can declare but not use an uninitialised local variable. In Java, the default value of any object is null.
Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor.
Simple: relying on default values does not communicate intent.
Did you really want that field to start with 0, or did you forget to assign a value?!
And of course, a null reference is half of the two things you need to run into a nullpointer exception.
Finally, using defaults implies that you have non final fields. Which you avoid where possible.
The only counter argument is: why write down things that you don't have to? But I think the listed disadvantages trumpet that, thus assigning 0 to a field explicitly is better than leaving it to the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With