Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it necessary that variables should be initialized to default values in Java

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

like image 812
swdeveloper Avatar asked Nov 03 '12 06:11

swdeveloper


1 Answers

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.

like image 192
Vikdor Avatar answered Sep 22 '22 23:09

Vikdor