In the first scenario, the list object is declared outside the while loop, which again works indefinitely (like while (true)), so it continues to add until it runs out of memory, and in the second, because you declared the list inside while, the maximum size is limited by the number of iterations of the for loop.
Each time a for loop exists, the reset list object that is created is new to which you start adding, so you have an upper limit. The old object is garbage collection that cleans up the JVM.
Saurabh jhunjhunwala
source share