Java primitives always have a default value in the memory of O (booleans are false = 0). So why is it considered as a bad practise to not initialize them, if they even have a predefined value because of this mechanic? And in arrays, even with initialization of a new int[8], all the values in it arent really initialized, but that isnt frowned upon...
A constructor is typically used to initialize instance variables representing the main properties of the created object. If we don't supply a constructor explicitly, the compiler will create a default constructor which has no arguments and just allocates memory for the object.
The instance variable is declared inside a class but not within any method, constructor, block etc. If we don't initialize an instance variable, then JVM automatically provide default value according to the data type of that instance variable.
If you declare a variable as final, it is mandatory to initialize it before the end of the constructor. If you don't you will get a compilation error.
Java designers believe every variable should be properly initialized. To initialize a variable is to give it a correct initial value. It's so important to do this that Java either initializes a variable for you, or it indicates an error has occurred, telling you to initialize a variable.
By explicitly defining a value, it's clear that you intended that value at that point of execution. If not, another reader might interpret it as if you either forgot to initialize this variable or you don't care at that point (and will set it somewhere else later).
In other words, it's some kind of implicit documentation. Generally, it's considered better practice to write verbose code for better readability; i.e. never use abbreviations for methods names, write them out!
Also, if you have to write line comments (//
), you can almost always replace them by wrapping the following code into a well-named method. Implicit documentation ftw! :)
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