class CounterClass{
int count=0;//will get memory when instance is created
CounterClass(){
count++;
System.out.println(count);
}
public static void main(String args[]){
CounterClass c1=new CounterClass();
CounterClass c2=new CounterClass();
CounterClass c3=new CounterClass();
}
}
/*
problem with instance variable:
instance variable gets the memory at the time of object creation,
each object will have the copy of the instance variable, if it is
incremented, it won't reflect to other objects. So each objects will
have the value 1 in the count variable.
*/
1
1
1
Press any key to continue . . .
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.