I have a simple for loop in which I create new objects and save to list. After this loop I never used these objects again. Will Java remove these objects from heap or keep them alive before method end because of there are (in stack area) will be several local variables of OrderItem type?
for (int i = 0; i < arr.length; i++) {
OrderItem item = new OrderItem();
item.setProduct(product);
item.setQuantity(entry.getValue());
orderItemList.add(item);
}
Or these objects will live in heap until end of a method (method frame).
But what if move declaration of OrderItem item
outside the loop.
OrderItem item;
for (int i = 0; i < arr.length; i++) {
item = new OrderItem();
item.setProduct(someValue);
item.setQuantity(someValue);
orderItemList.add(item);
}
As I understand correctly, in this case in stack area there is only one local variable of OrderItem type and on each loop iteration this variable will reference to new object. And for objects from previous iterations there are no references and these objects should be removed from heap.