In an article about how objects are initialized in Java there was a paragraph which is given below:
At the beginning of an object's life, the Java virtual machine (JVM) allocates enough memory on the heap to accommodate the object's instance variables. When that memory is first allocated, however, the data it contains is unpredictable. If the memory were used as is, the behavior of the object would also be unpredictable. To guard against such a scenario, Java makes certain that memory is initialized, at least to predictable default values, before it is used by any code.
Can anyone kindly explain that what is meant by unpredictable data
and unpredictable behavior
here. Thanks in advance
Can anyone kindly explain that what is meant by unpredictable data and unpredictable behavior here.
If you programmed in C/C++, you would notice that an uninitialized variable carries some garbage value, present in the memory location allocated to it, interpreted as per the data type of the variable. The compiler doesn't complain about such variables and if the developer forgets to initialize them properly, the garbage values gets used, resulting in unexpected behavior of the program.
In Java, the JVM initializes all member variables to the default values based on the data type of the variable and complains about local variables that are not initialized during compilation, to avoid such unexpected behavior and making the developer always use initialized variables.
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