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:
Integer i;
i = new Integer(); // 1. create new object and make reference variable i refer to it.
i = new Integer(); // 2. create another object and make reference variable i refer to it...there is no way to get to the object created in step1 so obj in step 1 is eligible for GC.
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:
class Test {
public static void main(String...args) {
Vector v = new Vector(); // create a new vector.
while(true) {
v.addElement(new Integer(1)); // create a new Integer and add it to vector.
}
}
}
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.