If I have a method inside a class and I am creating an object inside that method
then would that object be destroyed and the memory allocated to it released
once the method is finished?
eg. –
public void drawFigure(){
Paint paint = new Paint();
paint.setSomeProperty();
canvas.drawLine(startPoint, finishPoint, paint);
}
So after the method drawFigure is complete, paint object will be destroyed ?
which same as paint = null, but I do not need it to be set to null,
because it is a local object. Am I right?
It is not guaranteed that object will be GCed as soon as method call is done, but object will become as eligible for GC and on next GC run it may be collected and memory will be free.
EDIT:
Yes you are correct. You don’t need to set it to
null. Local variables will be created on stack and stack will be removed as soon as method is completed. So, paint will go away from memory andnew Paint()object will be on heap without any references, which makes above object as eligible for GC.See this youtube video by Standford professor.