Eager Initialization & Lazy Initialization
Concept-wise, a good programming practice is lazy initialization; but both have their own importance in coding.
There are two types of initializations in a programming language –
- eager initialization and
- lazy initialization
In eager initialization, the object is created in the program execution, in a normal way, which sometimes the programmer may not use it in the program.
This results waste of memory & processor time.
Other way is to create the object is by lazy initialization That is, create when the programmer really requires.
That is, if the object is created at runtime, only when the programmer requires is known as lazy initialization.
Lazy initialization is basically meant for improving the performance by avoiding unnecessary computation (load on the microprocessor) and reducing memory requirements.
I am giving very simple example here to explain
Example:
snippet 1:
// Eager initialization
Record createRecord ( int age ) {
Record record = new Record (); // Eager Initialization
if ( age >= 18 ) {
record.setAge (age);
return record;}
return null;
}
In the above code, Record object inside the method created but not used if age falls less than 18. In this you can say that amount of memory used in the heap at that instance processor excution is wasted.
So we can say that Memory & Processor time utilized is completely wasted.
snippet 2:
// Lazy initialization
Record createRecord ( int age ) {
Record record = null;
if ( age >= 18 ) {
record = new Record (); // Lazy Initialization
record.setAge (age);
}return record;
}
In the above code, Record object inside the condition ( age >= 18 ) hence here the object creation happens only when ever it is required.
In this you can say that amount of memory used in the heap at that instance processor execution is used effectively & efficiently.

