I was trying to study different exceptions in Java and came across the OutOfMemoryError and I wanted to see it in work so I wrote the following program to create infinite objects by creating them in a infinite loop. The program does go in infinite loop it does not throw the OutOfMemoryError exception.
class Test {
public static void main(String...args) {
while(true) {
Integer i = new Integer();
}
}
}
You are on the right track. The only thing you are missing is the concept of garbage collection. The program does infact create infinite Integer objects but after the 1st iteration, the object created in the previous iteration becomes eligible for GC.
Consider this:
If you want to see the OutOfMemoryError you need to somhow make sure that there is a way to get to the objects created in the infinite loop. So you can do something like:
In this program Integer objects are created infinitely as before but now I add them to a vector so ensure that there is a way to get to them and they do not become GC eligible.